In some situations, you may want to detect if an application is blocked. For example, when you are automating Microsoft Internet Explorer, you may want to know if Internet Explorer has stopped responding.
This article describes how to detect whether an automated instance of Internet Explorer has stopped responding (hung) and how to close Internet Explorer. Although the code is written for Internet Explorer and Visual Basic .NET or Visual Basic 2005, you can use this approach for other applications as well.
The first three sections in this article outline the three important coding concepts that are necessary to accomplish this task. The fourth section demonstrates how to build the sample application.
Start the Application
The sample for this article uses Internet Explorer as the test application. The following code starts Internet Explorer and uses the
GetProcessByName method to get a handle to the process.
Browser = New InternetExplorer()
Browser.Visible = True
Browser.GoHome()
procs = Process.GetProcessesByName("IEXPLORE")
Determine If the Application Is Responding
The following code checks the first element in the array
procs, which the
GetProcessByName method returns, to determine if the process is responding. This article assumes that only one instance of Internet Explorer is running. You must use the
try-catch block to handle the exception that is thrown if the process does not exist.
Try
If procs(0).Responding = True Then
MessageBox.Show("IEXPLORE is responding")
Else
MessageBox.Show("IEXPLORE is not responding")
End If
Catch
MessageBox.Show("IEXPLORE is not running")
End Try
Close the Application
The following code demonstrates how to close the application. If the application is still responsive, you can use the
CloseMainWindows method of the
Process class to close it. If the application is not responsive, you must call the
Kill method.
Try
If procs(0).Responding Then
procs(0).CloseMainWindow()
Else
'Force closure.
procs(0).Kill()
End If
Catch notRunning As Exception When Err.Number = 91
MessageBox.Show("Could Not Find the IEXPLORE Process")
End Try
Build the Sample Project
About the Sample
The sample project in this article consists of a form with the following three buttons:
- Start Internet Explorer, which uses Automation to start an instance of Internet Explorer.
- Check Internet Explorer, which tests to see if the browser is responding.
- Close Internet Explorer, which closes the browser.
If you want to give this code a thorough test and know of a Web page that will cause the browser to stop responding, you can browse to that page after you open the browser. Then, try to click
Check Internet Explorer and
Close Internet Explorer. Allow a few moments after you click the buttons; the response is not immediate when the browser is unresponsive.