天天看点

怎样在Winform窗体中嵌入Web浏览器

背景

项目当中需要在Winform窗体中嵌入网页,虽然微软自带了WebBrowser控件,但是她是以IE模式运行的,兼容性实在太差,找了一圈发现有个叫CefSharp的家伙还不错,于是就拿来玩了一下。

CefSharp 主要特征

  • 支持.NET Framework 4.5.2+
  • 支持Winform,WPF
  • 基于Chromium内核
  • 支持Javascript互操作
  • BSD商业开源,地址https://github.com/cefsharp/CefSharp

快速入门

注:笔者的环境是Visual Studio 2019.

  • 新建winform项目。
  • 打开Nuget包管理器。
  • 搜索CefSharp.WinForms,可以看到目前最新的版本是81.x, 点击安装。
  • 编译项目,会出现以下错误:
    CefSharp.Common is unable to proceeed as your current Platform is ‘AnyCPU’. To target AnyCPU please read https://github.com/cefsharp/CefSharp/issues/1714. Alternatively change your Platform to x86 or x64 and the relevant files will be copied automatically. For details on changing your projects Platform see https://docs.microsoft.com/en-gb/visualstudio/ide/how-to-configure-projects-to-target-platforms?view=vs-2017

这是因为编译的时候默认使用的AnyCPU选项,官方也给出了不同的解决方案,根据其中一种做了以下修改:

  • 用文本工具打开项目文件,找到第一个PropertyGroup节点,添加子节点:<CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>
  • 修改App.Config,添加probing节点,修改后如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath="x86"/>
      </assemblyBinding>
    </runtime>
</configuration>
           
  • 修改Program的Main函数,如下:
static void Main()
    {
        var settings = new CefSettings();
        settings.BrowserSubprocessPath =System.IO.Path.GetFullPath(@"x86\CefSharp.BrowserSubprocess.exe");

        Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
           
  • 最后在Form里面嵌入浏览器控件即可:
public Form1()
{
    InitializeComponent();

    ChromiumWebBrowser browser = new ChromiumWebBrowser("http://www.bigname65.com");
    browser.Dock = DockStyle.Fill;
    this.Controls.Add(browser);
}
           

继续阅读