Click here to Skip to main content
15,880,469 members
Articles / Desktop Programming / WPF

Configuring the Emulation Mode of an Internet Explorer WebBrowser Control

Rate me:
Please Sign up or sign in to vote.
4.96/5 (20 votes)
6 Jul 2014MIT6 min read 197.3K   4.6K   31   37
Helper class for configuring which version of Internet Explorer is used by the WebBrowser control when hosted in a Windows Forms or WPF application

Background

Occasionally, I need to embed HTML in my applications. If it is just to display some simple layout with basic interactions, I might use a component such as HtmlRenderer. In most cases however, I need a more complex layout, JavaScript or I might want to display real pages from the internet - in which case I'm lumbered with the WebBrowser control.

I'm aware other embeddable browsers exist, but the idea of shipping additional multi-MB dependencies doesn't make sense unless an application makes heavy use of HTML interfaces.

The WebBrowser control annoys me in myriad ways, but it does get the job done. One of the things that occasionally frustrates me is that by default, it is essentially an embedded version of Internet Explorer 7 - or enabling Compatibility Mode in a modern IE session. Not so good as more and more sites use HTML5 and other goodies.

Rather fortunately however, Microsoft provides the ability to configure the emulation mode your application will use. It's not as simple as setting some properties on a control as it involves setting some registry values and other caveats, but it is still a reasonable process.

Do you really want to greet your users with script errors when displaying modern websites in the WebBrowser control?

About Browser Emulation Versions

The table below (source) lists the currently supported emulation versions at the time of writing. As you can see, it's possible to emulate all "recent" versions of Internet Explorer in one of two ways - either by forcing a standards mode, or allowing !DOCTYPE directives to control the mode. The exception to this dual behaviour is version 7 which is as is.

According to the documentation, the IE8 (8000) and IE9 (9000) modes will switch to IE10 (10000) mode if installed. The documentation doesn't mention if this is still the case regarding IE11 so I'm not sure about the behaviour in that regard.

Value Description
11001 Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.
11000 IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.
10001 Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
10000 Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
9999 Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
9000 Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
8888 Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
8000 Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8
7000 Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.

Setting the Browser Emulation Version

Browser emulation support is configured in the Registry

Setting the emulation version is very straightforward - add a value to the registry in the below key containing the name of your executable file and a value from the table above.

HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
   SOFTWARE
      Microsoft
         Internet Explorer
            Main
               FeatureControl
                  FEATURE_BROWSER_EMULATION
                     yourapp.exe = (DWORD) version

Note: If you do this from an application you're debugging using Visual Studio and the Visual Studio Hosting Process option is enabled, you'll find the executable name may not be what you expect. When enabled, a stub process with a slightly modified name is used instead. For example, if your application is named calc.exe, you'll need to add the value calc.vshost.exe in order to set the emulated version for the correct process.

Getting the Internet Explorer Version

As it makes more sense to detect the version of IE installed on the user's computer and set the emulation version to match, first we need a way of detecting the IE version.

There are various ways of getting the installed IE version, but the sensible method is reading the value from the registry as everything else we are doing in this article involves the registry in some fashion.

HKEY_LOCAL_MACHINE
   SOFTWARE
      Microsoft
         Internet Explorer
            svcVersion or Version

Older versions of IE used the Version value, while newer versions use svcVersion. In either case, this value contains the version string.

We can use the following code to pull out the major digit.

C#
private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";

public static int GetInternetExplorerMajorVersion()
{
  int result;

  result = 0;

  try
  {
    RegistryKey key;

    key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);

    if (key != null)
    {
      object value;

      value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);

      if (value != null)
      {
        string version;
        int separator;

        version = value.ToString();
        separator = version.IndexOf('.');
        if (separator != -1)
        {
          int.TryParse(version.Substring(0, separator), out result);
        }
      }
    }
  }
  catch (SecurityException)
  {
    // The user does not have the permissions required to read from the registry key.
  }
  catch (UnauthorizedAccessException)
  {
    // The user does not have the necessary registry rights.
  }

  return result;
}

Points to Note

  • I'm returning an int with the major version component rather a Version class. In this example, I don't need a full version to start with and it avoids crashes if the version string is invalid
  • For the same reason, I'm explicitly catching (and ignoring) SecurityException and UnauthorizedAccessException exceptions which will be thrown if the user doesn't have permission to access those keys. Again, I don't really want the function crashing for those reasons.

You can always remove the try block to have all exceptions thrown instead of the access exceptions being ignored.

Getting the Browser Emulation Version

By using Internet Explorer's browser emulation support, we can choose how the WebControl behaves

The functions to get and set the emulation version are using HKEY_CURRENT_USER to make them per user rather than for the entire machine.

First, we'll create an enumeration to handle the different versions described above so that we don't have to deal with magic numbers.

C#
public enum BrowserEmulationVersion
{
  Default = 0,
  Version7 = 7000,
  Version8 = 8000,
  Version8Standards = 8888,
  Version9 = 9000,
  Version9Standards = 9999,
  Version10 = 10000,
  Version10Standards = 10001,
  Version11 = 11000,
  Version11Edge = 11001
}

Next, a function to detect the current emulation version in use by our application, and another to quickly tell if an emulation version has previously been set.

C#
private const string BrowserEmulationKey = 
    InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";

public static BrowserEmulationVersion GetBrowserEmulationVersion()
{
  BrowserEmulationVersion result;

  result = BrowserEmulationVersion.Default;

  try
  {
    RegistryKey key;

    key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
    if (key != null)
    {
      string programName;
      object value;

      programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
      value = key.GetValue(programName, null);

      if (value != null)
      {
        result = (BrowserEmulationVersion)Convert.ToInt32(value);
      }
    }
  }
  catch (SecurityException)
  {
    // The user does not have the permissions required to read from the registry key.
  }
  catch (UnauthorizedAccessException)
  {
    // The user does not have the necessary registry rights.
  }

  return result;
}

public static bool IsBrowserEmulationSet()
{
  return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
}

Setting the Emulation Version

And finally, we need to be able to set the emulation version. I've provided two functions for doing this, one which allows you to explicitly set a value, and another that uses the best matching value for the installed version of Internet Explorer.

C#
public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
{
  bool result;

  result = false;

  try
  {
    RegistryKey key;

    key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);

    if (key != null)
    {
      string programName;

      programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);

      if (browserEmulationVersion != BrowserEmulationVersion.Default)
      {
        // if it's a valid value, update or create the value
        key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
      }
      else
      {
        // otherwise, remove the existing value
        key.DeleteValue(programName, false);
      }

      result = true;
    }
  }
  catch (SecurityException)
  {
    // The user does not have the permissions required to read from the registry key.
  }
  catch (UnauthorizedAccessException)
  {
    // The user does not have the necessary registry rights.
  }

  return result;
}

public static bool SetBrowserEmulationVersion()
{
  int ieVersion;
  BrowserEmulationVersion emulationCode;

  ieVersion = GetInternetExplorerMajorVersion();

  if (ieVersion >= 11)
  {
    emulationCode = BrowserEmulationVersion.Version11;
  }
  else
  {
    switch (ieVersion)
    {
      case 10:
        emulationCode = BrowserEmulationVersion.Version10;
        break;
      case 9:
        emulationCode = BrowserEmulationVersion.Version9;
        break;
      case 8:
        emulationCode = BrowserEmulationVersion.Version8;
        break;
      default:
        emulationCode = BrowserEmulationVersion.Version7;
        break;
    }
  }

  return SetBrowserEmulationVersion(emulationCode);
}

As mentioned previously, I don't really want these functions crashing for anticipated reasons, so these functions will also catch and ignore SecurityException and UnauthorizedAccessException exceptions. The SetBrowserEmulationVersion function will return true if a value was updated.

Simple Usage

If you just want "fire and forget" updating of the browser emulation version, you can use the following lines.

C#
if (!InternetExplorerBrowserEmulation.IsBrowserEmulationSet())
{
  InternetExplorerBrowserEmulation.SetBrowserEmulationVersion();
}

This will apply the best matching IE version if an emulation version isn't set. However, it means if the user updates their copy if IE to something newer, your application will potentially continue to use the older version. I shall leave that as an exercise for another day!

Caveats and Points to Note

Changing the Emulation Version While Your Application is Running

While experimenting with this code, I did hit a major caveat.

In the original application this code was written for, I was applying the emulation version just before the first window containing a WebBrowser control was loaded, and this worked perfectly well.

However, setting the emulation version doesn't seem to work if an instance of the WebBrowser control has already been created in your application. I tried various things such as recreating the WebBrowser control or reloading the Form the control was hosted on, but couldn't get the new instance to honour the setting without an application restart.

The attached demonstration program has gone with the "restart after making a selection" hack - please don't do this in production applications!

Should I Change the Emulation Version of my Application?

You should carefully consider where or not to change the emulation version of your application. If it's currently working fine, then it's probably better to leave it as is. If however, you wish to make use of modern standards compliant HTML, CSS or JavaScript, then setting the appropriate emulation version will save you a lot of trouble.

Further Reading

The are a lot of different options you can apply to Internet Explorer and the WebBrowser control. These options allow you to change behaviours, supported features and quite a few more. This article has touched upon one of the more common requirements, but there are a number of other options that are worth looking at for advanced application scenarios.

An index of all available configuration options can be found on MSDN.

History

  • 28/06/2014 - First published on cyotek.com
  • 06/07/2014 - Published on CodeProject

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDo you have a VB version (or more simply, a DLL version)? Pin
Robert Gustafson29-Dec-18 6:44
Robert Gustafson29-Dec-18 6:44 
AnswerThanks for an Awesome Article Pin
Member 137006014-Apr-18 20:45
Member 137006014-Apr-18 20:45 
QuestionHow to set registry key with Win8.X and 10 Pin
jesus198027-Sep-16 22:59
jesus198027-Sep-16 22:59 
GeneralMy vote of 5 Pin
Michal Krzych20-Sep-16 8:33
Michal Krzych20-Sep-16 8:33 
PraiseYou are a freaking life saver! Pin
Member 430183224-Dec-15 19:51
Member 430183224-Dec-15 19:51 
QuestionSo when I cannot read opensubkey Pin
buihoang91tin24-Sep-15 4:18
buihoang91tin24-Sep-15 4:18 
GeneralYou're my hero! Pin
stoneSolutions11-Sep-15 19:29
stoneSolutions11-Sep-15 19:29 
GeneralRe: You're my hero! Pin
Richard James Moss11-Sep-15 20:25
professionalRichard James Moss11-Sep-15 20:25 
Questionbrilliant Pin
Member 5417519-Sep-15 3:56
Member 5417519-Sep-15 3:56 
AnswerRe: brilliant Pin
Richard James Moss11-Sep-15 20:23
professionalRichard James Moss11-Sep-15 20:23 
QuestionThanx Pin
Robert Stallmann25-Aug-15 1:44
Robert Stallmann25-Aug-15 1:44 
AnswerRe: Thanx Pin
Richard James Moss25-Aug-15 1:56
professionalRichard James Moss25-Aug-15 1:56 
QuestionWindows 10 Pin
fas123x9-Aug-15 22:10
fas123x9-Aug-15 22:10 
AnswerRe: Windows 10 Pin
Richard James Moss10-Aug-15 9:25
professionalRichard James Moss10-Aug-15 9:25 
Questionhow can handle the memory leak problem Pin
prithvirajn3-Aug-15 23:03
prithvirajn3-Aug-15 23:03 
AnswerRe: how can handle the memory leak problem Pin
Richard James Moss4-Aug-15 6:17
professionalRichard James Moss4-Aug-15 6:17 
QuestionTwo browser controls in one app, each needs different emulation Pin
Chris J. Kennedy23-Jun-15 11:08
Chris J. Kennedy23-Jun-15 11:08 
AnswerRe: Two browser controls in one app, each needs different emulation Pin
Richard James Moss24-Jun-15 6:07
professionalRichard James Moss24-Jun-15 6:07 
GeneralRe: Two browser controls in one app, each needs different emulation Pin
Chris J. Kennedy2-Jul-15 8:32
Chris J. Kennedy2-Jul-15 8:32 
SuggestionAnother registry entry for 32bit ie under a 64bit os Pin
Jens Theisen16-Jan-15 4:45
Jens Theisen16-Jan-15 4:45 
GeneralRe: Another registry entry for 32bit ie under a 64bit os Pin
Richard James Moss17-Jan-15 2:34
professionalRichard James Moss17-Jan-15 2:34 
BugDoes not work with IE 11 Pin
Member 112190249-Nov-14 5:06
Member 112190249-Nov-14 5:06 
AnswerRe: Does not work with IE 11 Pin
Richard James Moss9-Nov-14 5:28
professionalRichard James Moss9-Nov-14 5:28 
Well, I have to disagree. Given that I developed it on a machine with IE11 and with which is working perfectly.

Have you checked to see that it is using the correct values (for example debug mode with the Visual Studio host process enabled as per my comments in the article)? Or that you have the correct permissions to modify the registry. Or that you aren't setting it after already creating a WebBrowser control?

Regards;
Richard Moss
GeneralRe: Does not work with IE 11 Pin
Member 112190249-Nov-14 5:46
Member 112190249-Nov-14 5:46 
AnswerRe: Does not work with IE 11 Pin
Richard James Moss6-Dec-14 21:11
professionalRichard James Moss6-Dec-14 21:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.