Well, after looking at the feature in Visual Studio 2013 well introduced by my buddy Abhijit, I was thinking to do the similar thing from application as well. I thought if I could build a tool how could I mimic the same behavior to send refresh signal to an opened process from my application.
It seem to me pretty straight- forward, we can make use of SendKeys
interface to generate the similar behavior.
Let us create a WPF Application, put a Textbox and two buttons :
The UI looks pretty straightforward too.
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Text="Url" /> <TextBox x:Name="txtUrl" Grid.Column="1"/> <Button Click="Button_Click" Content="Open Url" Grid.Row="1" Grid.ColumnSpan="2" /> <Button Click="Refresh_click" Content="Refresh" Grid.Row="2" Grid.ColumnSpan="2" /> </Grid>
Now to deal with the SendKeys
, you need to add System.Windows.Forms
to the project, or otherwise you need to PInvoke manually to SendInput.
Once this is done, let us write some code.
[DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr hWnd); Process process = null; private void Button_Click(object sender, RoutedEventArgs e) { Process proc = new Process(); proc.StartInfo.FileName = "iexplore.exe"; proc.StartInfo.Arguments = this.txtUrl.Text; proc.Start(); this.process = proc; } private void Refresh_click(object sender, RoutedEventArgs e) { if (this.process != null) { IntPtr ptr = this.process.MainWindowHandle; SetForegroundWindow(ptr); SendKeys.SendWait("{F5}"); } }
For simplicity, I have kept the code as simple as I could. Here I just used a Process to call iexplore.exe(Internet Explorer)
with an argument to an url. Thus when the Button_Click
is called (Open Link
), it will open Internet explorer and open the website specified on the URL textbox. We keep the Process object separately in a variable for future reference.
Now to send a Refresh key (which is defined as F5 in IE or any other browser) you need to first activate the application first. There is an API defined as SetForegroundWindow
which activates an HWnd. We can get this Window handle from the Process object using MainWindowHandle. When this is passed, the application gets deactivated and the IExplorer
process gets reactivated. The SendKeys.SendWait will send the key F5 to the browser and wait for its full refresh.
Thus when you click on the second button, it will refresh the browser.
Now if you are creating a Webserver or an HTTP parser, you can refresh the output in the browser using the above code.
The code is not optimized, but suitable to get basic concept. Just like this, the approach can be used to send keys to any application.
Pingback: FireFox OS Developer Featured In The Daily Six Pack: September 3, 2013