在 webbrowser 控件中使用最新版本的 Internet Explorer

Posted

技术标签:

【中文标题】在 webbrowser 控件中使用最新版本的 Internet Explorer【英文标题】:Use latest version of Internet Explorer in the webbrowser control 【发布时间】:2013-07-29 03:22:59 【问题描述】:

C# Windows Forms 中 webbrowser 控件的默认版本 应用程序是 7。我已经通过文章 Browser Emulation 更改为 9,但是如何在 webbrowser 控件中使用已安装的 Internet Explorer 的最新版本?

【问题讨论】:

【参考方案1】:

我看到了 Veer 的回答。我认为这是对的,但它并没有为我工作。也许我正在使用 .NET 4 并且正在使用 64x 操作系统,所以请检查一下。

您可以在应用程序启动时进行设置或检查:

private void Form1_Load(object sender, EventArgs e)

    var appName = Process.GetCurrentProcess().ProcessName + ".exe";
    SetIE8KeyforWebBrowserControl(appName);


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();
    

你可能会发现 messagebox.show,只是为了测试。

键如下:

11001 (0x2AF9) - Internet Explorer 11。网页在 IE11 中显示 边缘模式,与!DOCTYPE 指令无关。

11000 (0x2AF8) - Internet Explorer 11. 网页包含 基于标准的!DOCTYPE 指令在 IE11 边缘模式下显示。 IE11 的默认值。

10001 (0x2711)- Internet Explorer 10。网页以 IE10 标准显示 模式,无论!DOCTYPE 指令如何。

10000 (0x2710)- Internet Explorer 10. 包含基于标准的网页 !DOCTYPE 指令以 IE10 标准模式显示。默认 Internet Explorer 10 的值。

9999 (0x270F) - Internet Explorer 9。网页在 IE9 中显示 标准模式,与 !DOCTYPE 指令无关。

9000 (0x2328) - Internet Explorer 9. 包含 基于标准的!DOCTYPE 指令以 IE9 模式显示。

8888 (0x22B8) - 网页以 IE8 标准模式显示, 不管!DOCTYPE 指令如何。

8000 (0x1F40) - 包含基于标准的网页!DOCTYPE 指令以 IE8 模式显示。

7000 (0x1B58) - 包含基于标准的网页!DOCTYPE 指令以 IE7 标准模式显示。

参考:MSDN: Internet Feature Controls

我看到像 Skype 这样的应用程序使用 10001。我不知道。

注意

安装应用程序将更改注册表。您可能需要在清单文件中添加一行以避免由于注册表更改权限而导致的错误:

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

更新 1

这是一个类将在 windows 上获取最新版本的 IE 并进行应有的更改;

public class WebBrowserHelper



    public static int GetEmbVersion()
    
        int ieVer = GetBrowserVersion();

        if (ieVer > 9)
            return ieVer * 1000 + 1;

        if (ieVer > 7)
            return ieVer * 1111;

        return 7000;
     // End Function GetEmbVersion

    public static void FixBrowserVersion()
    
        string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
        FixBrowserVersion(appName);
    

    public static void FixBrowserVersion(string appName)
    
        FixBrowserVersion(appName, GetEmbVersion());
     // End Sub FixBrowserVersion

    // FixBrowserVersion("<YourAppName>", 9000);
    public static void FixBrowserVersion(string appName, int ieVer)
    
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
     // End Sub FixBrowserVersion 

    private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
    
        try
        
            //For 64 bit Machine 
            if (Environment.Is64BitOperatingSystem)
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
            else  //For 32 bit Machine 
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);


        
        catch (Exception)
        
            // some config will hit access rights exceptions
            // this is why we try with both LOCAL_MACHINE and CURRENT_USER
        
     // End Sub FixBrowserVersion_Internal 

    public static int GetBrowserVersion()
    
        // string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
        string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
        string[] ls = new string[]  "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" ;

        int maxVer = 0;
        for (int i = 0; i < ls.Length; ++i)
        
            object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
            string strVal = System.Convert.ToString(objVal);
            if (strVal != null)
            
                int iPos = strVal.IndexOf('.');
                if (iPos > 0)
                    strVal = strVal.Substring(0, iPos);

                int res = 0;
                if (int.TryParse(strVal, out res))
                    maxVer = Math.Max(maxVer, res);
             // End if (strVal != null)

         // Next i

        return maxVer;
     // End Function GetBrowserVersion 



使用类如下

WebBrowserHelper.FixBrowserVersion();
WebBrowserHelper.FixBrowserVersion("SomeAppName");
WebBrowserHelper.FixBrowserVersion("SomeAppName",intIeVer);

您可能在 Windows 10 的可比性方面遇到问题,这可能是由于您的网站本身造成的 您可能需要添加此元标记

<meta http-equiv="X-UA-Compatible" content="IE=11" >

享受:)

【讨论】:

来自 MSDN:“注册表重定向器通过在 WOW64 上提供注册表某些部分的单独逻辑视图来隔离 32 位和 64 位应用程序。注册表重定向器拦截 32 位和 64 位注册表调用它们各自的逻辑注册表视图并将它们映射到相应的物理注册表位置。重定向过程对应用程序是透明的。因此,32 位应用程序可以访问注册表数据,就好像它在 32 位 Windows 上运行一样,即使数据存储在 64 位 Windows 上的不同位置”您无需担心 Wow6432Node 你也可以使用HKEY_CURRENT_USER,不需要管理员。 一个建议:将Environment.Is64BitOperatingSystem 更改为Environment.Is64BitProcess @JobaDiniz 请检查更新 1 会帮助你:) 我知道这已经有几年的历史了,但对于未来的读者:您的应用程序不需要检查它是否在 64 位系统甚至 64 位进程中运行。 64 位版本的 Windows 实现了 Registry Redirector,它将自动将在 64 位系统上运行的 32 位应用程序重定向到 Wow6432Node 子项。您的应用程序不需要做任何额外的事情来适应这个“新”键。【参考方案2】:

使用来自MSDN的值:

  int BrowserVer, RegVal;

  // get the installed IE version
  using (WebBrowser Wb = new WebBrowser())
    BrowserVer = Wb.Version.Major;

  // set the appropriate IE version
  if (BrowserVer >= 11)
    RegVal = 11001;
  else if (BrowserVer == 10)
    RegVal = 10001;
  else if (BrowserVer == 9)
    RegVal = 9999;
  else if (BrowserVer == 8)
    RegVal = 8888;
  else
    RegVal = 7000;

  // set the actual key
  using (RegistryKey Key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree))
    if (Key.GetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe") == null)
      Key.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe", RegVal, RegistryValueKind.DWord);

【讨论】:

老兄,这是获取版本的一种更简单的方法...谢谢,这对我有用! 谢谢,很好的代码,除了应该使用CreateSubKey 而不是OpenSubKey,因为如果密钥不存在,OpenSubKey 将返回 null。 好点!我编辑了答案以使用 CreateSubKey 并仅在尚未设置值时设置值。 太棒了!太感谢了。这应该是最好的答案。尝试了上面的怪物解决方案,但没有区别。这接近了它。再次感谢! @MarkNS 好吧,在这种情况下,您可以先进行空检查,然后再进行版本检查,然后再编写。其背后的逻辑只是为了避免不断写入注册表,但如果您对此感到满意,您可以简单地删除空检查。【参考方案3】:
var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
    Key.SetValue(appName, 99999, RegistryValueKind.DWord);

根据我在这里读到的内容 (Controlling WebBrowser Control Compatibility:

如果我在客户端将 FEATURE_BROWSER_EMULATION 文档模式值设置为高于 IE 版本会怎样?

显然,浏览器控件只能支持小于或等于客户端安装的IE版本的文档模式。使用 FEATURE_BROWSER_EMULATION 键最适用于部署了浏览器并支持版本的企业业务线应用程序。 如果您将该值设置为比客户端上安装的浏览器版本更高的浏览器模式,浏览器控件将选择可用的最高文档模式。

最简单的就是放一个很高的十进制数...

【讨论】:

注意:如果您在win64上运行32位应用程序,则需要编辑的密钥在SOFTWARE\WOW6432Node\Microsoft...下。它会在代码中自动重定向,但如果您打开 regedit,可能会让您大吃一惊。 短小甜甜。对我来说Registry.LocalMachine.OpenSubKey(".. 以管理员身份在 Win2012 服务器上工作。 @bendecko,您的应用程序需要管理员权限。 /!\ 不要使用此解决方案 /!\ 因为如果您使用导航(到本地文件)并且您的 html 内容位于 Intranet 区域中(例如:使用MOTW 到本地主机)。使用 99999 与使用 11000 的行为相同。要解决我上面提到的问题,您需要 11001。【参考方案4】:

我可以在 HTML 的标题中添加一行,而不是更改 RegKey:

<html>
    <head>
        <!-- Use lastest version of Internet Explorer -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

        <!-- Insert other header tags here -->
    </head>
    ...
</html>

Web Browser Control & Specifying the IE Version

【讨论】:

虽然这种技术有效,但它不会提供相同的用户代理。使用FEATURE_BROWSER_EMULATION 技术,我得到Mozilla/5.0 (Windows NT 6.2; Win64; x64; ... 而使用X-UA-Compatible 技术,我得到Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; ...,Google Analytics 将其检测为移动设备。 谢谢!当您只需要托管一个本地页面时工作得非常好(因此用户代理字符串完全不相关)。【参考方案5】:

你可以试试这个link

try

    var IEVAlue =  9000; // can be: 9999 , 9000, 8888, 8000, 7000
    var targetApplication = Processes.getCurrentProcessName() + ".exe"; 
    var localMachine = Registry.LocalMachine;
    var parentKeyLocation = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl";
    var keyName = "FEATURE_BROWSER_EMULATION";
    "opening up Key: 0 at 1".info(keyName, parentKeyLocation);
    var subKey = localMachine.getOrCreateSubKey(parentKeyLocation,keyName,true);
    subKey.SetValue(targetApplication, IEVAlue,RegistryValueKind.DWord);
    return "all done, now try it on a new process".info();

catch(Exception ex)

    ex.log();
    "NOTE: you need to run this under no UAC".info();

【讨论】:

string ver = (new WebBrowser()).Version.ToString(); 好,我只是想在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer 中检查注册表,但这种方式更简单。谢谢 Processes.getCurrentProcessName() 是什么?可能是Process.GetCurrentProcess().ProcessName localMachine.getOrCreateSubKey 是什么?不存在? 你也可以使用HKEY_CURRENT_USER,不需要管理员。【参考方案6】:

这里是我通常使用并为我工作的方法(适用于 32 位和 64 位应用程序;ie_emulation 可以是此处记录的任何人:Internet Feature Controls (B..C), Browser Emulation):

    [STAThread]
    static void Main()
    
        if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
        
            // Another application instance is running
            return;
        
        try
        
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var targetApplication = Process.GetCurrentProcess().ProcessName  + ".exe";
            int ie_emulation = 10000;
            try
            
                string tmp = Properties.Settings.Default.ie_emulation;
                ie_emulation = int.Parse(tmp);
            
            catch  
            SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);

            m_webLoader = new FormMain();

            Application.Run(m_webLoader);
        
        finally
        
            mutex.ReleaseMutex();
        
    

    private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
    
        RegistryKey Regkey = null;
        try
        
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);

            // If the path is not correct or
            // if user haven't privileges to access the registry
            if (Regkey == null)
            
                YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
                return;
            

            string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

            // Check if key is already present
            if (FindAppkey == "" + ieval)
            
                YukLoggerObj.logInfoMsg("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
                Regkey.Close();
                return;
            

            // If a key is not present or different from desired, add/modify the key, key value
            Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);

            // Check for the key after adding
            FindAppkey = Convert.ToString(Regkey.GetValue(appName));

            if (FindAppkey == "" + ieval)
                YukLoggerObj.logInfoMsg("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
            else
                YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION setting failed; current value is  " + ieval);
        
        catch (Exception ex)
        
            YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);

        
        finally
        
            // Close the Registry
            if (Regkey != null)
                Regkey.Close();
        
    

【讨论】:

【参考方案7】:

我能够实施 Luca 的解决方案,但我必须进行一些更改才能使其正常工作。我的目标是将 D3.js 与 Windows 窗体应用程序的 Web 浏览器控件一起使用(针对 .NET 2.0)。它现在对我有用。我希望这可以帮助其他人。

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;

namespace ClientUI

    static class Program
    
        static Mutex mutex = new System.Threading.Mutex(false, "jMutex");

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        
            if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
            
                // Another application instance is running
                return;
            
            try
            
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
                int ie_emulation = 11999;
                try
                
                    string tmp = Properties.Settings.Default.ie_emulation;
                    ie_emulation = int.Parse(tmp);
                
                catch  
                SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);

                Application.Run(new MainForm());
            
            finally
            
                mutex.ReleaseMutex();
            
        

        private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
        
            RegistryKey Regkey = null;
            try
            
                Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);

                // If the path is not correct or
                // if user doesn't have privileges to access the registry
                if (Regkey == null)
                
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
                    return;
                

                string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                // Check if key is already present
                if (FindAppkey == ieval.ToString())
                
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
                    Regkey.Close();
                    return;
                

                // If key is not present or different from desired, add/modify the key , key value
                Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);

                // Check for the key after adding
                FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                if (FindAppkey == ieval.ToString())
                
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
                
                else
                
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is  " + ieval);
                
            
            catch (Exception ex)
            
                MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
            
            finally
            
                //Close the Registry
                if (Regkey != null) Regkey.Close();
            
        
    

另外,我在项目设置中添加了一个字符串 (ie_emulation),值为 11999。该值似乎适用于 IE11(11.0.15)。

接下来,我必须更改我的应用程序的权限以允许访问注册表。这可以通过向您的项目中添加一个新项目来完成(使用 VS2012)。在常规项目下,选择应用程序清单文件。将级别从 asInvoker 更改为 requireAdministrator(如下所示)。

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

如果阅读本文的人试图将 D3.js 与网络浏览器控件一起使用,您可能必须修改 JSON 数据以存储在 HTML 页面内的变量中,因为 D3.json 使用 XmlHttpRequest(更易于与网络服务器一起使用)。在这些更改和上述更改之后,我的 Windows 窗体能够加载调用 D3 的本地 HTML 文件。

【讨论】:

【参考方案8】:

结合 RooiWillie 和 MohD 的答案 并记住以管理员权限运行您的应用程序。

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

RegistryKey Regkey = null;
try

    int BrowserVer, RegVal;

    // get the installed IE version
    using (WebBrowser Wb = new WebBrowser())
        BrowserVer = Wb.Version.Major;

    // set the appropriate IE version
    if (BrowserVer >= 11)
        RegVal = 11001;
    else if (BrowserVer == 10)
        RegVal = 10001;
    else if (BrowserVer == 9)
        RegVal = 9999;
    else if (BrowserVer == 8)
        RegVal = 8888;
    else
        RegVal = 7000;

    //For 64 bit Machine 
    if (Environment.Is64BitOperatingSystem)
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
    else  //For 32 bit Machine 
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

    //If the path is not correct or 
    //If user't have priviledges to access registry 
    if (Regkey == null)
    
        MessageBox.Show("Registry Key for setting IE WebBrowser Rendering Address Not found. Try run the program with administrator's right.");
        return;
    

    string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

    //Check if key is already present 
    if (FindAppkey == RegVal.ToString())
    
        Regkey.Close();
        return;
    

    Regkey.SetValue(appName, RegVal, RegistryValueKind.DWord);

catch (Exception ex)

    MessageBox.Show("Registry Key for setting IE WebBrowser Rendering failed to setup");
    MessageBox.Show(ex.Message);

finally

    //Close the Registry 
    if (Regkey != null)
        Regkey.Close();

【讨论】:

正如人们之前指出的那样,使用本地机器密钥注册限制管理员安装应用程序,而当前用户密钥允许普通用户安装应用程序。后者更灵活【参考方案9】:

一种廉价且简单的解决方法是,您可以在 FEATURE_BROWSER_EMULATION 键中放置一个大于 11001 的值。然后它需要系统中可用的最新 IE。

【讨论】:

【参考方案10】:

只需将以下内容添加到您的 html 中就不需要注册表设置了

<meta http-equiv="X-UA-Compatible" content="IE=11" >

【讨论】:

如何将 head 元标记添加到 WebBrowser?我无法添加注册表,因为我的应用程序将作为默认 shell(作为独立应用程序 Web 浏览器)在用户帐户上运行【参考方案11】:

Visual Basic 版本:

Private Sub setRegisterForWebBrowser()

    Dim appName = Process.GetCurrentProcess().ProcessName + ".exe"
    SetIE8KeyforWebBrowserControl(appName)
End Sub

Private Sub SetIE8KeyforWebBrowserControl(appName As String)
    'ref:    http://***.com/questions/17922308/use-latest-version-of-ie-in-webbrowser-control
    Dim Regkey As RegistryKey = Nothing
    Dim lgValue As Long = 8000
    Dim strValue As Long = lgValue.ToString()

    Try

        'For 64 bit Machine 
        If (Environment.Is64BitOperatingSystem) Then
            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)
        End If


        'If the path Is Not correct Or 
        'If user't have priviledges to access registry 
        If (Regkey Is Nothing) Then

            MessageBox.Show("Application Settings Failed - Address Not found")
            Return
        End If


        Dim FindAppkey As String = Convert.ToString(Regkey.GetValue(appName))

        'Check if key Is already present 
        If (FindAppkey = strValue) Then

            MessageBox.Show("Required Application Settings Present")
            Regkey.Close()
            Return
        End If


        'If key Is Not present add the key , Kev value 8000-Decimal 
        If (String.IsNullOrEmpty(FindAppkey)) Then
            ' Regkey.SetValue(appName, BitConverter.GetBytes(&H1F40), RegistryValueKind.DWord)
            Regkey.SetValue(appName, lgValue, RegistryValueKind.DWord)

            'check for the key after adding 
            FindAppkey = Convert.ToString(Regkey.GetValue(appName))
        End If

        If (FindAppkey = strValue) Then
            MessageBox.Show("Registre de l'application appliquée avec succès")
        Else
            MessageBox.Show("Échec du paramètrage du registre, Ref: " + FindAppkey)
        End If
    Catch ex As Exception


        MessageBox.Show("Application Settings Failed")
        MessageBox.Show(ex.Message)

    Finally

        'Close the Registry 
        If (Not Regkey Is Nothing) Then
            Regkey.Close()
        End If
    End Try
End Sub

【讨论】:

【参考方案12】:

我知道这已经发布,但这是我使用的 dotnet 4.5 以上的当前版本。我建议使用尊重 doctype 的默认浏览器仿真

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl

    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    
        _processName = $"Process.GetCurrentProcess().ProcessName.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive  get; set;  = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        
            using (var key = currentUser.CreateSubKey($"RegistryLocation\\featureControl", false))
            
                if (key.GetValue(_processName) is int value)
                
                    return value;
                
                return -1;
            
        
    

    private void SetFeatureControl(string featureControl, int value)
    
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        
            using (var key = currentUser.CreateSubKey($"RegistryLocation\\featureControl", true))
            
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            
        
    

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    
        get
        
            if (_version.Major < 8)
                throw new NotSupportedException($"AboutProtocolRestriction requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        
        set
        
            if (_version.Major < 8)
                throw new NotSupportedException($"AboutProtocolRestriction requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        
    

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    
        get
        
            if (_version.Major < 8)
                throw new NotSupportedException($"nameof(BrowserEmulation) requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            
                return (DocumentMode)value;
            
            return DocumentMode.NotSet;
        
        set
        
            if (_version.Major < 8)
                throw new NotSupportedException($"nameof(BrowserEmulation) requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        
    

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    
        get
        
            if (_version.Major < 9)
                throw new NotSupportedException($"nameof(GpuRendering) requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        
        set
        
            if (_version.Major < 9)
                throw new NotSupportedException($"nameof(GpuRendering) requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        
    

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    
        get
        
            if (_version.Major < 7)
                throw new NotSupportedException($"nameof(LocalScriptBlocking) requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        
        set
        
            if (_version.Major < 7)
                throw new NotSupportedException($"nameof(LocalScriptBlocking) requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        
    

    #endregion


    private DocumentMode DefaultRespectDocType
    
        get
        
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            
        
    

    private DocumentMode DefaultOverrideDocType
    
        get
        
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            
        
    


internal enum DocumentMode

    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000

【讨论】:

用它做什么?..如何使用它?什么时候打电话? 如果你愿意,你可以在第一次代码午餐时调用它。使用codeInternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;'为了更好地了解这是在哪里拉的,您可以查看msdn.microsoft.com/en-us/ie/… 还要添加注释,这个不需要管理员权限来启用。它还将根据位数选择正确的注册表并设置文档显示的相同限制。比如 GPU 渲染需要 IE 9 才能工作【参考方案13】:

最好强制使用最高模式。这可以通过添加:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

为了支持 IE,最好包含 polyfill 库:

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>

在任何脚本之前。

【讨论】:

【参考方案14】:

现在可以使用WebView2 形式的更好解决方案。 WebView2 控件使用基于 Chromium 的 Microsoft Edge 作为呈现引擎在本机应用程序中显示 Web 内容。此控件可用于Winforms 以及WPF 应用程序中。

要在Winforms 中使用它,只需安装Microsoft.Web.WebView2 NugetPackage。之后,WebView2 将可用于您的应用程序!

更多详情here。

【讨论】:

以上是关于在 webbrowser 控件中使用最新版本的 Internet Explorer的主要内容,如果未能解决你的问题,请参考以下文章

WebBrowser控件是浏览器啥版本

delphi强制WebBrowser控件使用指定版本显示网页

WebBrowser 控件不呈现某些页面

WebBrowser控件默认使用IE9,IE10的方法

非 IE WebBrowser ActiveX 控件

如何让webbrowser控件支持Html5