溫故知新,遇見CefSharp,適用於WPF/WinFroms的Chromium嵌入框架的C#版本,讓客戶端插上Web的翅膀


什么是Cef

https://github.com/chromiumembedded/cef

Chromium Embedded Framework (CEF). A simple framework for embedding Chromium-based browsers in other applications.

image

嵌入式Chromium框架(簡稱CEF) ,全稱Chromium Embedded Framework,是一個由Marshall Greenblatt在2008建立的開源項目,它主要目的是開發一個基於Google Chromium的Web Browser控件。CEF支持一系列的編程語言和操作系統,並且能很容易地整合到新的或已有的工程中去。

image

市面上,很多主流的瀏覽器都是都是以這種嵌入Chromium內核的方式進行研發,包括微軟最新的作品Microsoft Edge。

https://www.chromium.org

image

它的設計思想是易用且兼顧性能。CEF基本的框架包含C/C++程序接口,通過本地庫的接口來實現,而這個庫則會隔離宿主程序和Chromium & Webkit的操作細節。它在瀏覽器控件和宿主程序之間提供緊密的整合,它支持用戶插件、協議、Javascript對象以及Javascript擴展,宿主程序可以隨意地控件資源下載,導航,下下文內容和打印等,並且可以跟Google Chrome瀏覽器一起,支持高性能和Html5技術。

其源碼https://bitbucket.org/chromiumembedded/cef/src/master/

什么是CefSharp

https://cefsharp.github.io

CefSharp is a simple .Net wrapper around the Chromium Embedded Framework (CEF). CEF is an open source project based on the Google Chromium project. Unlike the Chromium project itself, which focuses mainly on Google Chrome application development, CEF focuses on facilitating embedded browser use cases in third-party applications. CEF is based on the multi-process Chromium Content API and as a result only a subset of the features that exist in Chromium are currently available. For example, support for extensions is limited, only a subset of the Extension API is implemented.

CefSharp嵌入式Chromium框架(Chromium Embedded Framework)的C#實現版本,讓基於.Net的Windows客戶端能方便的把Chromium核心嵌入其中,滿足Hybrid混合架構的業務場景需求,終端技術目前支持:WinFromsWPFOffScreen,.Net框架不僅支持.Net Framework,還支持最新的.Net Core 3.1 / Net 5

CefSharp provides three different flavors, WinForms, WPF and OffScreen. The WPF and OffScreen versions use the OffScreen Rendering(OSR) rendering mode. In OSR mode each frame is rendered to a buffer and then either drawn on the screen as in the case of WPF or available as a Bitmap in the OffScreen. All versions use the CefSharp and CefSharp.Core libraries, as a result much of the API is used exactly the same within all three flavors. This limits code duplication and reduces the maintenance burden of adding a new feature, the only downside is the WPF version is not quite as WPF friendly as it could be (you can subclass the ChromiumWebBrowser class and implement any missing parts in your application that are required). Also you can host the WinForms version within WPF using the WindowsFormsHost, this may be required to get around some limitations of the WPF version (CEF has yet to implement full touch screen support in the OSR mode, there is an open issue on the CEF Issue Tracker, if this is something you require, get involved there).

Off-Screen Rendering 離屏渲染,指的是GPU在當前屏幕緩沖區以外新開辟一個緩沖區進行渲染操作

CefSharp的WPF和OffScreen版本使用了離屏渲染機制(OffScreen Rendering, OSR),但是在OSR模式下,Cef暫時沒有全觸屏的接口支持,所以WPF版本還是存在一些限制,如果有必要你可以在WPF中可通過WindowsFormsHost技術來嵌入WinForms版,所有的版本都將使用CefSharpCefSharp.Core這兩個庫。

image

安裝環境

https://github.com/cefsharp/CefSharp/releases

軟件環境要求:

關於支持AnyCPU:

最新版本已經支持AnyCPU了,細節參見:https://github.com/cefsharp/CefSharp/issues/1714

官方示例

https://github.com/cefsharp/CefSharp.MinimalExample

勤學勤練

https://github.com/TaylorShi/HelloCefSharp

如果Visual Studio 2019打不開,需要前往工具-選項-環境-預覽功能中,找到使用.Net SDK預覽版這個選項並且勾選上。

image

創建解決方案及目錄

  1. 新建名為HelloCefSharp的解決方案
dotnet new sln -o HelloCefSharp

image

  1. 切換到HelloCefSharp目錄
cd .\HelloCefSharp\

image

創建.Net Core的WinFroms項目

  1. 創建名為demoForWinFormCoreWinFroms項目
dotnet new winforms -o demoForWinFormCore -f net5.0

image

  1. 添加demoForWinFormCore到解決方案
dotnet sln add .\demoForWinFormCore\demoForWinFormCore.csproj

image

  1. 切換到demoForWinFormCore目錄
cd .\demoForWinFormCore\

image

  1. 運行demoForWinFormCore項目
dotnet watch run

image

創建.Net Core的WPF項目

  1. 創建名為demoForWpfCoreWinFroms項目
dotnet new wpf -o demoForWpfCore

image

  1. 添加demoForWpfCore到解決方案
dotnet sln add .\demoForWpfCore\demoForWpfCore.csproj

image

  1. 切換到demoForWpfCore目錄
cd .\demoForWpfCore\

image

  1. 運行demoForWpfCore項目
dotnet watch run

image

創建.Net Framework的WinFroms項目

  1. 創建名為demoForWinFormFrameWinFroms項目

image

這里需要將框架最低設置為:.Net Framework 4.5.2,這是目前CefSharp的WinForms包最低兼容版本。

image

  1. 運行demoForWinFormFrame項目

image

創建.Net Framework的Wpf項目

  1. 創建名為demoForWpfFrameWinFroms項目

image

image

  1. 運行demoForWpfFrame項目

image

.Net Core的WinFroms項目安裝CefSharp包

https://www.nuget.org/packages/CefSharp.WinForms.NETCore

dotnet add package CefSharp.WinForms.NETCore

image

image

運行試試:

dotnet watch run

image

.Net Core的WPF項目安裝CefSharp包

https://www.nuget.org/packages/CefSharp.Wpf.NETCore

dotnet add package CefSharp.Wpf.NETCore

image

運行試試:

dotnet watch run

image

.Net Framework的WinFroms項目安裝CefSharp包

https://www.nuget.org/packages/CefSharp.WinForms

在Visual Studio的demoForWinFormFrame項目上右鍵管理Nuget程序包,搜索關鍵詞CefSharp.WinForms找到對應的包進行安裝即可。

image

安裝后新增文件packages.config

image

運行試試:

image

.Net Framework的Wpf項目安裝CefSharp包

https://www.nuget.org/packages/CefSharp.Wpf

在Visual Studio的demoForWpfFrame項目上右鍵管理Nuget程序包,搜索關鍵詞CefSharp.Wpf找到對應的包進行安裝即可。

image

安裝后新增文件packages.config

image

運行試試:

image

Wpf項目添加ChromiumWebBrowser控件

https://github.com/cefsharp/CefSharp/wiki/Quick-Start

demoForWpfFrame項目的MainWindow.xaml文件中。

1. 新增引用CefSharp.Wpf的命名空間

xmlns:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"

2. 添加ChromiumWebBrowser控件即可,其中Address便是啟動時加載的網址設定

<Window
    x:Class="demoForWpfFrame.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:demoForWpfFrame"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">

    <Border>
        <wpf:ChromiumWebBrowser x:Name="Browser" Address="www.bing.com" />
    </Border>

</Window>

3. 運行效果

image

4. .Net Core的Wpf項目同理

image

WinFroms項目添加ChromiumWebBrowser控件

https://github.com/cefsharp/CefSharp/wiki/Quick-Start

demoForWinFormFrame項目中,雙擊打開MainForm.cs,展開窗體設計器。

image

1. 在Visual Studio的視圖菜單中啟用工具箱視圖。

image

這樣我們便可以在工具箱中看到CefSharp提供的兩個瀏覽器嵌入控件了。

image

2. 我們選取ChromiumWebBrowser控件拖入右側的窗體設計器中,默認他會以填充的形式加入進入,改名控件為Browser

image

3. 接下來我們在MainForm.csLoad事件中加載指定的初始化網址即可。

namespace demoForWinFormFrame
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            Load += MainForm_Load;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Browser.Load("www.bing.com");
        }
    }
}

4. 運行效果

image

5. 或者在Main2Form.cs中先拖入一個名為MainPanel的Panel控件。

image

6. 然后在Main2Form.cs的Load事件中引入ChromiumWebBrowser控件,並且掛載到MainPanel下面。

namespace demoForWinFormFrame
{
    public partial class Main2Form : Form
    {
        public Main2Form()
        {
            InitializeComponent();
            Load += Main2Form_Load;
        }

        private void Main2Form_Load(object sender, EventArgs e)
        {
            var browser = new ChromiumWebBrowser("www.bing.com");
            MainPanel.Controls.Add(browser);
        }
    }
}

7. 運行效果

image

初始化並配置Cef、瀏覽器設置

https://github.com/cefsharp/CefSharp.MinimalExample/blob/master/CefSharp.MinimalExample.WinForms/Program.cs

https://github.com/cefsharp/CefSharp/wiki/General-Usage#1-how-do-you-call-a-javascript-method-from-net

/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
    InitCef();

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Main2Form());
}
private static void InitCef()
{
    #if ANYCPU
    CefRuntime.SubscribeAnyCpuAssemblyResolver();
    #endif

    //For Windows 7 and above, best to include relevant app.manifest entries as well
    Cef.EnableHighDPISupport();

    var settings = new CefSettings
    {

        // Increase the log severity so CEF outputs detailed information, useful for debugging
        LogSeverity = LogSeverity.Verbose,
        // By default CEF uses an in memory cache, to save cached data e.g. to persist cookies you need to specify a cache path
        // NOTE: The executing user must have sufficient privileges to write to this folder.
        CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
    };

    //Example of setting a command line argument
    //Enables WebRTC
    // - CEF Doesn't currently support permissions on a per browser basis see https://bitbucket.org/chromiumembedded/cef/issues/2582/allow-run-time-handling-of-media-access
    // - CEF Doesn't currently support displaying a UI for media access permissions
    //
    //NOTE: WebRTC Device Id's aren't persisted as they are in Chrome see https://bitbucket.org/chromiumembedded/cef/issues/2064/persist-webrtc-deviceids-across-restart
    settings.CefCommandLineArgs.Add("enable-media-stream");
    //https://peter.sh/experiments/chromium-command-line-switches/#use-fake-ui-for-media-stream
    settings.CefCommandLineArgs.Add("use-fake-ui-for-media-stream");
    //For screen sharing add (see https://bitbucket.org/chromiumembedded/cef/issues/2582/allow-run-time-handling-of-media-access#comment-58677180)
    settings.CefCommandLineArgs.Add("enable-usermedia-screen-capturing");

    //Perform dependency check to make sure all relevant resources are in our output directory.
    Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
}

image

var browser = new ChromiumWebBrowser("www.bing.com")
{
    BrowserSettings =
    {
        DefaultEncoding = "UTF-8",
        WebGl = CefState.Disabled
    }
};

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM