Starting an InPrivate instance of Internet Explorer in CodedUI

During the preparation of one of my CodedUI tests I came in situation in which I needed to start Internet Explorer with InPrivate Browsing set to active. There is no such a property on BrowserWindow object that can be set, probably because this is a specific Internet Explorer option (although present as functionality with a different name on other browsers). So how do we do it?

A quick search on Google, surprisingly, didn’t gave any results. So I dug into this small challenge.

In order to start Internet Explorer with InPrivate Browsing set to active it is necessary to pass the -private argument to the call of the executable. So how to pass an argument to the BrowserWindow instance that we are creating?

It’s not obvious as not often used but, BrowserWindow.Launch static method has, aside the usual signature accepting an Uri object as a parameter, an overload that accepts a variable number of string  arguments (params string[]). The string arguments specified in the call of this method, will be passed as arguments to the process that is going to be started by invoking the BrowserWindow.Launch, in this case to the process of Internet Explorer. This is quite handy as we can pass our URL and and the necessary -private argument to Internet Explorer and achieve the desired result.

BrowserWindow.Launch("", "-private");

How does it work?

If you peek inside the BrowserWindow class, you will see that underneath it is starting a process and it passes all of the parameters as an array of string to the Arguments property.

Process process = 
    new Process {StartInfo = {FileName = "iexplore.exe"}};
StringBuilder commandLine = new StringBuilder();
    str => commandLine.AppendFormat(
        "{0} ", 
        new object[] { str }));
process.StartInfo.Arguments = commandLine.ToString();

The same can be achieved also by using the following approach:

Process ieInPrivate = new Process();
ieInPrivate.StartInfo.FileName = "iexplore";
ieInPrivate.StartInfo.Arguments = " -private";
ieInPrivate.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;

BrowserWindow browser = BrowserWindow.FromProcess(ieInPrivate);

At the end the result will be a successfully launched Internet Explorer with InPrivate Browsing set to active.

There are also some other handy option that you can pass to Internet Explorer like -extoff that will start Internet Explorer in No Add-ons mode. For a complete list of options check the following page on MSDN.

Happy coding!