How to set IE9 by default for web browser? - c#

I am developing an application in C#.NET. I want to use the IE9 version for WebBrowser; either IE9 is installed on system or not.
Is it possible that using IE9 with WebBrower and it may be that IE9 is not installed in my system?

With Windows Internet Explorer 8 or later the FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet Explorer. Value 9999 - forces webpages to be displayed in IE9 Standards mode, regardless of the !DOCTYPE directive. You need IE9 or later installed on the target system. Check Internet Feature Controls (B..C)
private static void WebBrowserVersionEmulation()
{
const string BROWSER_EMULATION_KEY =
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
//
// app.exe and app.vshost.exe
String appname = Process.GetCurrentProcess().ProcessName + ".exe";
//
// Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
const int browserEmulationMode = 9999;
RegistryKey browserEmulationKey =
Registry.CurrentUser.OpenSubKey(BROWSER_EMULATION_KEY,RegistryKeyPermissionCheck.ReadWriteSubTree) ??
Registry.CurrentUser.CreateSubKey(BROWSER_EMULATION_KEY);
if (browserEmulationKey != null)
{
browserEmulationKey.SetValue(appname, browserEmulationMode, RegistryValueKind.DWord);
browserEmulationKey.Close();
}
}

Insert
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE="\9\" >"
Into your html page,but you have to know Web_browser control dependent on version of IE that already installed on target OS

For this, you have to lookup
What is the version of the underlying browser (registry key may return former installed version). Simplest code I use is asking the WebBrowser control
WebBrowser browser= new WebBrowser
Version ver= browser.Version(); // With ver.Major you can decide the EMULATION
The app-exe-name of your app (differs, while running in vs debug environment to "myapp".vshost.exe). This code I found somewhere:
// This code detects the .vshost. when running in vs ide
[DllImport("kernel32.dll", SetLastError=true)]
private static extern int GetModuleFileName([In]IntPtr hModule,
[Out]StringBuilder lpFilename,
[In][MarshalAs(UnmanagedType.U4)] int nSize);
public static String getAppExeName()
{
StringBuilder appname= new StringBuilder(1024);
GetModuleFileName(IntPtr.Zero, appname, appname.Capacity);
return Path.GetFileName(appname.ToString()); // return filename part
}
Now, you can calculate the Registry-Entry which is necessary for the browser compatibility. The Entry may be in Registry.LocalMachine (access rights required) or Registry.CurrentUser. I check the registry on every program start, so, I first test the existence of the entry
string regSubKey= #"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string version= "" + ver.Version + "0000"; // installed version x 10000
string appname= getAppExeName();
RegistryKey rs = Registry.CurrentUser.OpenSubKey(regSubKey);
keyval = rs.GetValue(appname);
rs.Close();
if (keyval != null && keyval.ToString().Equals(version))
return; // already done and no browser update installed.
//
// Create key for this app and this version
rs = Registry.LocalMachine.CreateSubKey(regSubKey);
rs.SetValue(app, sversion, RegistryValueKind.DWord);
rs.Flush();
rs.Close();
In 64bit + 32bit modes, may be you have to create an entry in "Software\Wow6432Node" too
After setting the registry key, the WebBrowser control should start with the required emulation

No, the webbrowser-element (I think you mean this) is on base of IE6. You only can start the process of IE9 (don't know the name but for firefox its simply "firefox.exe") form the program.

You can read the version from the registry:
var ieVersion = Registry.LocalMachine.OpenSubKey(#"Software\Microsoft\Internet Explorer").GetValue("Version");
or
If you have a WebBrowser control you can grab it from there:
WebBrowser browser = new WebBrowser();
Version ver = browser.Version;

Related

Display WebPage in C#

I want to display The webpage: http://vhg.cmp.uea.ac.uk/tech/jas/vhg2018/WebGLAv.html in Windows Form of my C# project.
I use WebBrowser tool in it and write this code to show this webpage in the Form:
webBrowser1.Navigate("http://vhg.cmp.uea.ac.uk/tech/jas/vhg2018/WebGLAv.html");
but it doesn't show the full webpage!
What should I've done?
By default Windows Forms applications use IE wrapper and not guarantee to use latest IE version. Read this article to know what happen behind IE wrappers and what Windows emulation key do.
This code from one of my old project let to change the default emulation version of IE for your executable process programmatically :
private static readonly string BrowserEmulationRegistryKeyPath =
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
/// <summary>
/// Add the process name to internet explorer emulation key
> /// i do this because the default IE wrapper dose not support the latest JS features
> /// Add process to emulation key and set a DWord value (11001) for it means we want use IE.11 as WebBrowser component
/// </summary>
public bool EmulateInternetExplorer()
{
using (
var browserEmulationKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationRegistryKeyPath,
true))
{
if (browserEmulationKey == null)
Registry.CurrentUser.CreateSubKey(BrowserEmulationRegistryKeyPath);
string processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
// Means emulation already added and we are ready to start
if (browserEmulationKey?.GetValue(processName) != null)
return true;
// Emulation key not exists and we must add it ( We return false because application restart to take effect of changes )
if (browserEmulationKey != null)
{
browserEmulationKey.SetValue(processName, 11001, RegistryValueKind.DWord);
browserEmulationKey.Flush();
}
return false;
}
}
If your website dose not show properly in latest Internet Explorer (not compatible) you should use other web browser wrappers like cefSharp that embed Chromium in your .Net app.
you can use google SDK to browse or using showing html content referee this
link

HTML5 on WebBrowser works slower than IE or other browser

I need to show HTML5 pages for WinForm and use component Webbrowser in mode emulation IE10.
When I open any hard page in Webbrowser I see it works slower than IE or other browsers.
For example
Uri uri = new Uri("http://createjs.com/demos/easeljs/Cache.html");
webBrowser.Url = uri;
webBrowser.Navigate(uri);
At http://createjs.com/demos/easeljs/Cache.html page if set "cache enabled" fps in IE10 > 60 but Webbrowser shows only 15 fps
Registry Mode Emulation IE10 for WebBrowser
private static void Emulation() // IE10
{
try
{
string keyName = #"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string valueName = System.AppDomain.CurrentDomain.FriendlyName;
RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, false);
object FindKey = Registry.GetValue("HKEY_LOCAL_MACHINE\\"+ keyName,System.AppDomain.CurrentDomain.FriendlyName,null);
if (FindKey == null)
{
RegistryKey RegistryKey = Registry.LocalMachine.CreateSubKey(keyName);
RegistryKey.SetValue(System.AppDomain.CurrentDomain.FriendlyName, 10001, RegistryValueKind.DWord);
}
}
catch (Exception Ex)
{
Console.WriteLine("Registry update error: " + Ex.Message);
Console.WriteLine("Can't change browser version.");
}
}
Any advice how to increase performance WebBrowser on WinForm?
What about using another Default Browser?
https://cefsharp.github.io/
Cefsharp is a port of Chromium to .NET! You can use it instead of IE...
Or you could this:
http://www.awesomium.com/#download
Awesomium is a HTML Engine...
You must set in the registry to use the latest IE version or Edge. Otherwise the oldest IE7 will be used.
Use latest version of Internet Explorer in the webbrowser control
When I updated IE from 10 to 11 version performance in component WebBrowser increased to the normal value.

C# webBrowser script error

I keep getting a script error when trying to load the page using webBrowser.Navigate("https://home.nest.com/"). It will pull up fine from my normal internet browser but not in my program.
Can anyone point me in the right direction?
as this link answer:
you must only add this line:
webBrowser.ScriptErrorsSuppressed = true;
The script errors happen all of the time in the integrated Internet Explorer WebBrowser control even when it's using version 11. Modern websites rely heavily on massive Javascript files and dynamic rendering. You can see that just by watching that page load in a regular browser. The control just can't cut it some of the times.
You might want to try some alternative browser controls. There are no guarantees that it will work with any of them, but at least it's something to try.
Awesomium : Originally based on Chromium. I don't know if they still integrate Chromium changes or if they've gone in their own direction. It's free for personal use as well as commercial making less than $100k.
DotNetBrowser : Embed a Chromium-based WPF / WinForms component into your .NET application to display modern web pages built with HTML5, CSS3, JavaScript, Silverlight etc.
geckofx : An open-source component for embedding Mozilla Gecko (Firefox) in .NET applications.
Xilium.CefGlue : A .NET/Mono binding for The Chromium Embedded Framework (CEF) by Marshall A. Greenblatt.
BrowseEmAll : BrowseEmAll.Cef (Chrome), BrowseEmAll.Gecko (Firefox), BrowseEmAll Core API (Chrome,Firefox,IE - COMMERCIAL)
There are probably others, but this should give you a start with some of the more popular active projects if you want to pursue this route.
The WebBrowser control is capable of rendering most web pages, but by default it attempts to render pages in compatibility mode (pretty much IE7, hence the issues). If you are building your own page, it's simple, just add the following tag to the header and it should render fine...
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
However, if you are trying to render a third party site you cannot add tags to, things get more difficult. As mentioned above, you can use a registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION) if it's just on your own machine.
If neither of these options are a possible solution, using a different browser control (again, great suggestions above) is pretty much your only option.
There's a great blog on controlling the browser control compatibility mode at https://learn.microsoft.com/en-gb/archive/blogs/patricka/controlling-webbrowser-control-compatibility
You should add your program name to the register HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
for using the latest feature as same as your normal internet browser.
as for me, value 8000 (0x1F40) - IE8 mode can solve many script error problem.
Ref:
Use latest version of Internet Explorer in the webbrowser control
private void Form1_Load(object sender, EventArgs e)
{
var appName = Process.GetCurrentProcess().ProcessName + ".exe";
SetIE8KeyforWebBrowserControl(appName);
webBrowser1.ScriptErrorsSuppressed = true;
}
private void SetIE8KeyforWebBrowserControl(string appName)
{
RegistryKey Regkey = null;
try
{
// For 64 bit machine
if (Environment.Is64BitOperatingSystem)
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(#"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
else //For 32 bit machine
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(#"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
// If the path is not correct or
// if the user haven't priviledges to access the registry
if (Regkey == null)
{
MessageBox.Show("Application Settings Failed - Address Not found");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
// Check if key is already present
if (FindAppkey == "8000")
{
MessageBox.Show("Required Application Settings Present");
Regkey.Close();
return;
}
// If a key is not present add the key, Key value 8000 (decimal)
if (string.IsNullOrEmpty(FindAppkey))
Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);
// Check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName));
if (FindAppkey == "8000")
MessageBox.Show("Application Settings Applied Successfully");
else
MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
}
catch (Exception ex)
{
MessageBox.Show("Application Settings Failed");
MessageBox.Show(ex.Message);
}
finally
{
// Close the Registry
if (Regkey != null)
Regkey.Close();
}
}
You may even set the registry value to 11000 to have the latest version of IE!!

selenium - internetexplorerdriver compatibility mode

Is there any way how to force webdriver/internetexplorerdriver to open a site in compatibility mode. Every time I run my tests by Nunit all the history and compatibility mode list (where was my site listed before) are cleaned.
I can't change the code of the site. Can I add item to compatibility mode list or open site in specifi version of IE (I have 11 and I need open it in 7 with doc type 5).
Unfortunately no, unless you change the source code. As a workaround I use VMS. If you want to use the same route consider using free VMs from Microsoft. See my another answer related to question here
This is better description of my issue: I need to test a site that I can't edit. The site works only in compatibility mode in my IE 11 (it is made for ie 7 doc type 5). I want to run tests and cookies should be cleaned before that. But if I set "EnsureCleanSession = true" it cleans compatibilty list in IE besides cookies. Because of it, it's not possible to test the site.
I have found possible solution, but I have to test it... I've found out that compatibility list is in registry and I can load its value before it is cleaned and set the value again:
const string keyName = #"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData";
var a = Registry.GetValue(keyName, "UserFilter" , "Return this default if NoSuchName does not exist.");
// value of registry is removed
Registry.SetValue(keyName, "UserFilter", a);
Console.ReadLine();
But as I said, I don't know if it will do the trick...
[UPDATE]
Ok, it works with small work-around (because IE must be restarted after change in registry)
[SetUp]
public void SetUp()
{
//read the compatibility mode list from registry
const string path = #"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData";
const string key = "UserFilter";
var regValue = Registry.GetValue(path, key, "Return this default if NoSuchName does not exist.");
//run IE driver with cleaning of cookies and history
var options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
EnsureCleanSession = true
};
_driver = new InternetExplorerDriver(IeDriversPath, options);
//cloase IE
_driver.Quit();
_driver.Dispose();
//put the compatibility mode list back into registry
Registry.SetValue(path, key, regValue);
//run IE driver without cleaning of cookies and history
options.EnsureCleanSession = false;
_driver = new InternetExplorerDriver(IeDriversPath, options);
}

Windows XP: where to write to registry from IE?

I need to read/write some information in the Windows registry from my BHO. On Windows Vista/7, I create a new key under HKEY_CURRENT_USER\Software\AppDataLow\Software. This works fine, even in protected mode.
However, it does not work on XP. I tried to change the registry to HKEY_CURRENT_USER\Software\Classes\Software or HKEY_CURRENT_USER\Software, no luck.
What is the right registry key to use on Windows XP from a BHO?
IEGetWriteableHKCU does not exist on Windows XP, it was first added in Windows Vista
Before Vista you will have to use a different approach... during installation of the BHO you need to tell Windows/IE which key(s) you want to be writable from the BHO...
There is a whole API family to handle this (supported from WinXP SP2 and up according to MSDN):
IERegisterWritableRegistryKey is used at installation time
IERegisterWritableRegistryValue is used at installation time
IERegCreateKeyEx is used at runtime
IERegSetValueEx is used at runtime
IE 7,8,9,(desktop)10 run tabs in "Protected Mode" which limits registry writes to special "writable" section. You need to ask IE for a pointer to it.
(C#)
// C# PInvoke declaration for needed IE method.
[DllImport("ieframe.dll")]
public static extern int IEGetWriteableHKCU(ref IntPtr phKey);
// ...
// somewhere inside other method:
IntPtr phKey = new IntPtr();
var answer = IEGetWriteableHKCU(ref phKey);
RegistryKey writeable_registry = RegistryKey.FromHandle(
new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
);
RegistryKey registryKey = writeable_registry.OpenSubKey(RegistryPathString, true);
if (registryKey == null) {
registryKey = writeable_registry.CreateSubKey(RegistryPathString);
}
registryKey.SetValue("Mode", mode);
writeable_registry.Close();
See:
About Protected Mode:
http://www.codeproject.com/Articles/18866/A-Developer-s-Survival-Guide-to-IE-Protected-Mode
About Enhanced Protected Mode:
http://blogs.msdn.com/b/ieinternals/archive/2012/03/23/understanding-ie10-enhanced-protected-mode-network-security-addons-cookies-metro-desktop.aspx

Categories

Resources