Opening and manipulating Internet Explorer windows programmatically

Today's Little Program takes the JavaScript application from a few years ago and converts it to C#. This was inspired by a customer who started with the question, "How can I close all Internet Explorer windows programmatically?"

This was a strange request. After all, the user may be rather upset that their Amazon shopping spree was suddenly terminated mid-stream.

Upon closer questioning, the customer explained that they had a business process which, among other things, opened a bunch of Internet Explorer windows, and when the operation was over, they wanted to close the windows.

Okay, so they didn't really want to close all Internet Explorer windows. They just wanted to close the ones that they had opened.

Which is easy to do. In fact, it's a line-by-line translation of the JavaScript version!

class Program {
 public static void Main() {
   var ie = new SHDocVw.InternetExplorer();
   ie.Visible = true;

If you want to open a dozen browser windows and then close them later, then go ahead and open a dozen browser windows, and then close them when you're done.

class Program {
 public static void Main() {
  var windows = new System.Collections.Generic.
  for (int i = 0; i < 12; i++) {
   var ie = new SHDocVw.InternetExplorer();
   ie.Visible = true;

  // blah blah wait for user to finish business process
  // (We'll just sleep for a few seconds.)

  // Close all the windows
  foreach (var ie in windows) {

Actually, let's make it a bit more interesting. Suppose the intranet site sends you to the page http://contoso/finished.aspx when you finish submitting your Widget Exemption Request. We want to close the Internet Explorer window when that happens.

class Program {
 static void ProcessWidgetExemptionRequest() {
  var exit = new System.Threading.EventWaitHandle(
             false, System.Threading.EventResetMode.ManualReset);
  var ie = new SHDocVw.InternetExplorer();
  ie.Visible = true;

  ie.DocumentComplete += (object frame, ref object url) => {
   if (url as string == "http://contoso/finished.aspx") {
  // Wait for the user to finish submitting their Widget
  // Exemption Request.

  // Clean up the IE window

 public static void Main() {

The Process­Widget­Exemption­Request method creates an event that we will use to tell us when the user has finished the operation. We then create an Internet Explorer window, navigate it to the Exemption Request Web site, and hook up an anonymous function that listens for document completion events. Then we wait.

When we get a completion event that says that the user has reached the Finished page, we set our private event, which causes the wait to complete, at which point we clean up the Internet Explorer window and return to our caller.

You can try out this program yourself, but you probably want to change the URLs.

Comments (13)
  1. Tim says:

    Scripting Internet Explorer this way has been very useful to me in the past when some data that you need to scrape is hidden behind some web interface.

    I'm sure there are "better" ways to automate posting a few html forms and scraping the results, but the Internet Explorer API is very convenient and accessible to scripting (VBScript/JScript or PowerShell).

    It seems to get a little more fiddly with every release of IE, because they shut down bits of the API as security vulnerabilities are addressed.

  2. StefanH says:

    Is there any particular reason, why one would use

    new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);

    to create the exit event instead of

    new System.Threading.ManualResetEvent(false);

    or is it personal preference?

    [Neither. It was due to ignorance. Manual­Reset­Event would have been much better. -Raymond]
  3. Nick says:

    Manipulating IE programmatically has been very helpful in the past for automating some thing (I had a class-registration program that was fairly popular for a while when I was in college).  I especially enjoyed getting in and messing with the DOM and calling (!) Javascript functions on the page from my C# code.

    The only thing I found frustrating was navigating the documentation for the myriad of COM interfaces that represent all the different versions and iterations of IE.  IHTMLDocument, IHTMLDocument2, IHTMLDocument3, etc.  Though I imagine my frustration there probably just shows my inexperience with COM in general.

  4. xpclient says:

    I wish there was an option in Windows to prevent programmatically / automatically opening the default browser without user consent. Too many installers or apps use that to spam the user with their website links. Besides being annoying, I have lost my saved IE session so many times because the browser window automatically opened and I quickly closed it not realizing I needed to restore my saved tabs from the last session first and then close it again. Or when such an IE session is opened, it should be separate private session for that program only that doesn't affect the user's saved session.

  5. Amin Mohammadi says:

    Nice and helpful….i wonder how can i manipulate address and monitor and manage user entered adress

  6. Gabe says:

    Does this mechanism create a new IE process, use an existing one if available, or does it all work in-process?

  7. Neil says:

    If you combine the two examples you probably want to close the windows as they navigate to the finished page rather than waiting for them all to navigate.

    [Obligatory blog software gripe: the Post button is no longer in the tab order. Please refer to the accessibility guidelines. Thank you for your consideration.]

  8. Matt says:

    @Neil: The reason for it – in case anyone is wondering – is because the POST text is inside an A tag which does not have a HREF attribute, and hence is not tab-stop-able.

    The fix is simple. HREF="javascript:void(0)" will provide exactly the same effect as current, but will introduce a tab-stop on the POST button.

  9. @xpclient: There is. Various personal firewalls do it.

  10. ChrisR says:

    @xpclient, @Fleet Command:  If you are using Internet Explorer (at least v8 since that is what I have), this option can be found under Tools -> Options, General, Tabs section, Settings button.  There is an option group in the resulting popup dialog that specifies how IE should behave when opening links from external programs.

  11. Mark Sowul says:

    @Chris R – @xpclient's situation presumably is when the browser isn't running.  You have IE closed (your session is now saved), you install some stuff, it opens IE, and because you didn't reopen the previous session, when you close it again, that single page is now the saved session.

    @xpclient – but there is relief though:

    1) Start IE and kill it.  That will trigger crash recovery of tabs next time.

    2) Go to %localappdata%microsoftInternet ExplorerRecovery

    3) Use "Restore previous versions" to restore a copy of this, just copy over what's already there

    4) Inside .Active you'll see RecoveryStore.{Guid}, several of them

    5) Open Registry Editor, go to HKCUSoftwareMicrosoftInternet ExplorerRecoveryActive

    6) You'll probably see at least one of the GUIDs there.  In any event, for each of those RecoveryStore.{Guid}, add a REG_DWORD value with the name {GUID}.  For example, {32716C92-3987-11E3-988A-00163839A1D3} with value 0

    7) Next time you start IE, it will prompt you to restore your previous session because it "crashed".  It will use the RecoveryStore guids from the registry to determine what to restore, and voila.  If IE was not running when the shadow copy was taken, you may need to do the usual "restore previous session" also.  But some combo should get your session back.

    The removal of shadow copies is one significant reason why I refuse to touch Windows 8.

  12. Nick says:


    This is one of many reasons I use Firefox and the Session Manager addon. I know, now you have two (or three) problems, but sometimes long-term improvements have a greater upfront cost.


    I had no idea Windows 8 removed Shadow Copies ("Previous versions").  Microsoft says (…/hh848072%28v=vs.85%29.aspx):

    > Previous Versions were rarely used and negatively impacted the overall Windows performance; as a result the feature was removed. In Windows 8, these features are no longer available

    Just wow. Previous Versions were one of the killer features that pushed me away from XP. That's an astoundingly stupid decision.

  13. xpclient says:

    @Fleet Command, @ChrisR  It seems you don't get what the issue is. @Mark Sowul, you get it, but your solution is not "simplified". @Nick, yeah but for me, Firefox's usability is light years behind Internet Explorer.

Comments are closed.

Skip to main content