A simple fix for problems with Windows Forms WebBrowser

Do you run into this issue? Our Guest Blogger, Brent Challis has the fix for you!

 

I have been trying to use the Windows.Forms.WebBrowser control with Google maps to display the location where a photo was taken based on it’s Exif data.

My problem was that it just showed error messages indicating that it considered the browser was incompatible with the site.

After much hunting, I found that the problem is that the control uses the IE engine and the default compatibility level is too low for some web sites. The solution seemed to be very messy and seemed to involve hacking the registry to identify the specific application as being at a higher compatibility level. It all seemed extremely messy.

Fortunately for me, I was using PowerShell Studio from SAPIEN Technologies, Inc. at the time.

This is an application that looks very much like Visual Studio and works in the same way to design Windows Forms based applications with drag, drop and configure but all the code is written in PowerShell.

Fortunate, as while I hadn’t noticed it at first, when I dropped the WebBrowser control onto the forms design, besides adding the control it also added a helper function:

function Set-WebBrowserEmulation
{
	param
	(
		[ValidateNotNullOrEmpty()]
		[string]
		$ExecutableName = [System.IO.Path]::GetFileName([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)
	)
 
	#region Get IE Version
	$valueNames = 'svcVersion', 'svcUpdateVersion', 'Version', 'W2kVersion'
 
	$version = 0;
	for ($i = 0; $i -lt $valueNames.Length; $i++)
	{
		$objVal = [Microsoft.Win32.Registry]::GetValue('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer', $valueNames[$i], '0')
		$strVal = [System.Convert]::ToString($objVal)
		if ($strVal)
		{
			$iPos = $strVal.IndexOf('.')
			if ($iPos -gt 0)
			{
				$strVal = $strVal.Substring(0, $iPos)
			}
 
			$res = 0;
			if ([int]::TryParse($strVal, [ref]$res))
			{
				$version = [Math]::Max($version, $res)
			}
		}
	}
 
	if ($version -lt 7)
	{
		$version = 7000
	}
	else
	{
		$version = $version * 1000
	}
	#endregion
 
	[Microsoft.Win32.Registry]::SetValue('HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION', $ExecutableName, $version)
}

In the form’s load event I simply call the function with:

Set-WebBrowserEmulation

It does the registry work for me without me having to know what the executable’s name is and what version information to work with.

It was a wonderful find for me. -Brent Challis

Check out Brent’s personal blog here: https://bchallis.wordpress.com/2020/10/17/problems-with-the-windows-forms-webbrowser-control-and-a-simple-way-to-fix-it/