WinForm CefSharp(谷歌瀏覽器開源組件)


來源:https://blog.csdn.net/yh0503/article/details/86648682

簡介

CefSharp簡單來說就是一款.Net編寫的瀏覽器包,方便你在Winform和WPF中內嵌的Chrome瀏覽器組件。

資源

中文幫助文檔地址:https://github.com/cefsharp/CefSharp/wiki/CefSharp%E4%B8%AD%E6%96%87%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3

GitHub地址:傳送門
wiki幫助文檔地址:傳送門
CefSharp最小的示例工程:傳送門
gitter交流討論區:傳送門

 

快速入門

本文使用版本cefsharp/71

 

要求

Visual Studio with NuGet Package Manager (>=2010).

CefSharp45.0 和更新的版本,需要安裝 VC 2013 Redistributable Package x86

更早的版本需要安裝VC 2012 Redistributable Package x86

.Net Framework4.5.2

安裝

這塊安裝使用沒有想象的那么簡單,比較坑爹,各種修改配置,按照官網的A配置方案沒有搞定,按照B配置方案勉強部署成功(VS2013/VS2017)!對於外文不好的我,看着英文文檔腦殼疼。老外給的閉坑指南,但是感覺沒有啥卵用。下面就介紹一下B方案安裝部署的過程吧,A方案我就不講了,想看的請去上面的官網查看。
 

簡略測試部署過程

整個工程可在GitHub下載:傳送門

 

創建工程Test.App(Winform工程),將其中的Form1窗體刪掉。

創建工程Test.Chrome(類庫)。

在Test.Chrome工程添加NuGet引用,搜索CefSharp,選擇CefSharp.Winforms。

在解決方案上點配置管理器,將平台設置為x86或x64.

在Test.Chrome工程添加Form1窗體,添加CefSharp窗體相關的代碼。

Test.App添加Test.Chrome工程的引用,修改Program.cs文件,引用Test.Chrome工程的Form1窗體。

--------------------------------------------------------------------------------------------------------------------------------

首先是先搭建基本的開發環境。

1. 新建Winform應用程序。

2. 在解決方案管理器上,右鍵單擊引用,選擇“管理NuGet程序包”。

3. 點擊瀏覽選項卡,搜索CefSharp,在列表中選擇CefSharp.WinForms,安裝CefSharp包,會自動安裝相關引用包。

4. 打開引用列表,看到有CefSharp,CefSharp.Core,CefSharp.Winforms這三個包就OK了。

然后說一下基本的用法。先實現把ChromeWebBrowser嵌入到窗體中去並打開百度好了。

  public partial class FrmWebCefSharp : Form
    {
        public ChromiumWebBrowser chromeBrowser;

        public FrmWebCefSharp()
        {
            InitializeComponent();

            // Start the browser after initialize global component
            InitializeChromium();
        }

        private void FrmWebCefSharp_Load(object sender, EventArgs e)
        {

        }

        //初始化瀏覽器並啟動
        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            chromeBrowser = new ChromiumWebBrowser("https://www.baidu.com");
            // Add it to the form and fill it to the form window.
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;
        }

        //窗體關閉時,記得停止瀏覽器
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }        


    }

 然后再窗體構造函數中,InitializeComponent()之后調用InitializeChromium()方法,將browser添加到窗體中去。

這里要說一下,CefSharp這個開源項目,目前應該沒有辦法導入VS的工具箱(至少筆者沒成功),所以只能通過代碼方式創建對象,browser的事件,也都需要代碼注冊,不過只要不是太新的新手,應該很快就習慣了。

這樣運行就能打開百度的頁面了。

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

how-to來源:https://ourcodeworld.com/articles/read/173/how-to-use-cefsharp-chromium-embedded-framework-csharp-in-a-winforms-application

 

如何在Winforms應用程序中使用CefSharp(鉻嵌入式框架C#)

CefSharp是將功能完善的標准投訴網絡瀏覽器嵌入到C#或VB.NET應用程序中的最簡單方法。CefSharp具有用於WinForms和WPF應用程序的瀏覽器控件,以及用於自動化項目的無頭(屏幕外)版本。CefSharp基於Chromium Embedded Framework(Chrome瀏覽器的開源版本)。您可以在官方主頁上獲得有關CefSharp項目的更多信息

您可以將CefSharp 用作瀏覽器組件,而不必依賴用戶在Windows上安裝的Internet Explorer的版本,也可以將其用作應用程序的預定義用戶界面是的,您可以在winforms c#應用程序中使用HTML控件(按鈕,輸入),並根據需要使用CSS進行自定義(Bootstrap等)。

這是您使用HTML,Javascript和CSS制作漂亮的本機Windows應用程序的機會,讓我們開始吧。

在本文中,我們將使用CefSharp version 49.0,如果您想使用,CefSharp version +51我們將提供一些新版本需要了解的技巧。

要求

  • 帶NuGet軟件包管理器的Visual Studio(> = 2010)。

1)創建一個基本的Winforms應用並使用NuGet包添加CefSharp

像往常一樣創建一個Winforms應用程序,然后以最新版本的.NET Framework為目標,沒有困難不是嗎?在進行操作之前,請確保您的計算機已安裝:

否則,您會發現以下錯誤:

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in browser.exe Additional information: Could not load file or assembly 'CefSharp.Core.dll' or one of its dependencies.

現在,在創建之后,添加CefSharp。要添加CefSharp,請轉到Visual Studio右上角的解決方案資源管理器,然后右鍵單擊您的應用程序(在解決方案下方),然后選擇“管理NuGet程序包”。

CefSharp金塊包裝經理

當出現搜索菜單時,鍵入cefsharp,選擇WinForms發行版並安裝它。

與Visual Studio的每個版本一樣,界面可能有所不同,只需確保安裝位於nuget.org包源中的CefSharp發行的CefSharp.WinForms發行版,在本示例中,我們使用的是Visual Studio 2015

CefSharp NuGet軟件包

遵循安裝設置(接受熱安裝)。在安裝過程中,您應該在控制台中看到有關該過程的相關信息:

Attempting to gather dependency information for package 'CefSharp.WinForms.49.0.1' with respect to project 'embebbedChromium', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'CefSharp.WinForms.49.0.1' with DependencyBehavior 'Lowest'
Resolving actions to install package 'CefSharp.WinForms.49.0.1'
Resolved actions to install package 'CefSharp.WinForms.49.0.1'
  GET https://api.nuget.org/packages/cef.redist.x64.3.2623.1401.nupkg
  OK https://api.nuget.org/packages/cef.redist.x64.3.2623.1401.nupkg 29ms
Installing cef.redist.x64 3.2623.1401.
Adding package 'cef.redist.x64.3.2623.1401' to folder 'F:\C# Development\Winform projects\embebbedChromium\packages'
Added package 'cef.redist.x64.3.2623.1401' to folder 'F:\C# Development\Winform projects\embebbedChromium\packages'
Added package 'cef.redist.x64.3.2623.1401' to 'packages.config'
Successfully installed 'cef.redist.x64 3.2623.1401' to embebbedChromium
  GET https://api.nuget.org/packages/cef.redist.x86.3.2623.1401.nupkg
  OK https://api.nuget.org/packages/cef.redist.x86.3.2623.1401.nupkg 31ms
Installing cef.redist.x86 3.2623.1401.

每個人都喜歡成功的消息,對嗎?我做 !

繼續操作之前的重要提示:通常,對於最新版本的CefSharp,建議在安裝Nuget程序包后完全關閉Visual Studio,然后重新打開(因為這樣可以確保您的引用顯示出來並具有完整的智能感知能力),否則最終錯誤:

找不到類型或名稱空間名稱“ Cefsharp”(您是否缺少using指令或程序集引用?)

找不到CefSharp名稱空間

2)更改平台配置(x86,x64或AnyCPU)

成功安裝后,根據您使用的CefSharp的版本,您需要配置一些東西以使其運行:

A. CefSharp 51版及更高版本

在CefSharp 51中,您可以使用AnyCPU使用CefSharp,但是它不能單獨使用,因為您需要在2個特定文件中進行一些更改。首先,在項目中啟用“首選32位”選項,右鍵單擊解決方案資源管理器中的“屬性”項(或在工具欄中的“項目”>“項目屬性”中),然后轉到“ 構建”選項卡。在常規屬性中,選中“首選32位”選項:

首選32位Cefsharp

然后,搜索your-project-name.csproj文件,可以在文件<your-project-name>/<your-project-name>/your-project-name.csproj的第一個<PropertyGroup>中的以下標記中找到它

<CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>

您的*.csproj文件應如下所示:

CefSharp anyCPU支持

最后,修改App.config文件,文件在Visual Studio中項目的解決方案資源管理器中可見,並在配置標簽中添加以下標簽:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath="x86"/>
    </assemblyBinding>
</runtime>

然后,您的配置文件將如下所示:

CefSharp AnyCPU app.config文件

如果您需要更多幫助或無法修改這些文件,請在此處查看有關Github中AnyCPU的問題以獲取更多幫助

B. CefSharp 49和更早版本(x86或x64)

對於CefSharp 49或更舊的版本,您需要提供項目的體系結構,否則CefSharp將無法正常工作。繼續使用配置管理器更改項目的配置。

CefSharp不構建任何CPU

正如boromir所說,您項目的目標平台不能是anyCPU,它必須是x86或  x64,否則您的控制台將收到以下警告,並且您的應用程序將無法編譯。

CefSharp.Common does not work correctly on AnyCPU platform. You need to specify platform (x86 / x64).

繼續先在配置管理器中進行更改。右鍵單擊Visual Studio右上方區域的解決方案資源管理器(在解決方案中為Direct),然后選擇Configuration Manager

CefSharp配置管理器

並選擇與您的項目需求相匹配的平台:

正確的平台cefsharp

請注意,如果不存在x86或x64選擇<New...>選項,則需要創建它們,然后將其添加然后選擇。

在您的項目中對CefSharp進行基本配置之后,該項目將成功構建,因為我們擁有使用 Chrome   所需的一切現在,我們只需要添加到表單中並與代碼一起使用即可。

3.1。使用CEF(作為瀏覽器)

現在我們的應用程序已經支持CefSharp,我們只需要在代碼中使用它即可。使用以下命令將CefSharp導入代碼中:

using CefSharp;
using CefSharp.WinForms;

現在添加以下方法,並在您的類中創建一個類可訪問變量作為瀏覽器(以在其他方法中使用):

public ChromiumWebBrowser chromeBrowser;

public void InitializeChromium()
{
   CefSettings settings = new CefSettings();
   // Initialize cef with the provided settings
   Cef.Initialize(settings);
   // Create a browser component
   chromeBrowser = new ChromiumWebBrowser("http://ourcodeworld.com");
   // Add it to the form and fill it to the form window.
   this.Controls.Add(chromeBrowser);
   chromeBrowser.Dock = DockStyle.Fill;
}

並在您的類的InitializeComponent()函數之后執行它(通常在構造函數中):

public Form1()
{
     InitializeComponent();
     // Start the browser after initialize global component
     InitializeChromium();
}

不要忘記在FormClosing您的表單中關閉cef組件

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
     Cef.Shutdown();
}

現在,您的類應如下所示(請注意,該項目的名稱為embebbedChromium):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace embebbedChromium
{
    public partial class Form1 : Form
    {
        public ChromiumWebBrowser chromeBrowser;
 
        public Form1()
        {
            InitializeComponent();
            // Start the browser after initialize global component
            InitializeChromium();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            chromeBrowser = new ChromiumWebBrowser("http://ourcodeworld.com");
            // Add it to the form and fill it to the form window.
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }        
    }
}

現在啟動您的應用程序(F5)或在工具欄中單擊“開始”,您將看到如何在C#Winforms應用程序中加載“我們的代碼世界”。

我們在CefSharp瀏覽器中的代碼世界

恭喜你!您剛剛以其最基本的表達方式在應用程序中實現了CefSharp。我們建議您繼續閱讀框架文檔,並了解如何創建更出色的東西。

3.2。使用CEF(作為用戶界面)

在上一點中,您已經將CefSharp實現為瀏覽器組件。但是您還可以做更多的事情,現在我們將用本地文件實現純HTML,Javascript和CSS(引導)UI並使用它來處理System事物。

我們需要在我們的Visual Studio項目中包含HTML資產。您可以直接從Visual Studio或Windows資源管理器中創建它們,但通過Visual Studio則更容易,因為該文件夾會自動添加到項目資源中。

在這種情況下,我們將使用一個簡單的Bootstrap接口  (包括Bootstrap和jQuery),該接口由以下目錄組成:

資料夾路徑

在添加Visual Studio項目之后(右鍵單擊解決方案資源管理器,然后在該項目上,添加文件夾並在其中粘貼您的資源),該項目應如下所示:

Visual Studio資源瀏覽器

重要提示:現在,您需要選擇每個文件夾中的所有文件,並執行以下操作:

  • 選擇html,js,css文件夾內的所有資源。
  • 在底部將Copy to Output Directory設置Copy Always

始終復制

現在,我們需要設置CefSharp指向我們的index.html文件而不是一個webUrl。現在我們的資源位於項目中,因此您可以使用以下代碼來獲取資源的路徑:

請注意,您需要始終提供文件的完整本地路徑。由於普通項目需要能夠在任何地方工作,因此路徑相對於我們項目的可執行文件。

// Now instead use http://ourcodeworld.com as URL we'll use the "page" variable to load our local resource
String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);

但是,這還行不通,如果您現在嘗試執行您的應用,則會出現白屏。我們首先需要:

  1. 將要在Javascript中使用的C#類公開為一個對象。
  2. 允許使用本地文件(file://)。

我們將在Javascript中公開一個c#類,以便使用Javascript操作本機函數。我們需要創建一個新類,該類在構造函數中需要2個項目(ChromiumBrowserInstance和The Main Form)。此類將具有2個功能,一個用於啟動Chrome開發者工具,另一個用於啟動Windows(cmd.exe)的命令提示符。

該類應如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.Diagnostics;

namespace embebbedChromium
{
    class CefCustomObject
    {
        // Declare a local instance of chromium and the main form in order to execute things from here in the main thread
        private static ChromiumWebBrowser _instanceBrowser = null;
        // The form class needs to be changed according to yours
        private static Form1 _instanceMainForm = null;


        public CefCustomObject(ChromiumWebBrowser originalBrowser, Form1 mainForm)
        {
            _instanceBrowser = originalBrowser;
            _instanceMainForm = mainForm;
        }

        public void showDevTools()
        {
            _instanceBrowser.ShowDevTools();
        }

        public void opencmd()
        {
            ProcessStartInfo start = new ProcessStartInfo("cmd.exe", "/c pause");
            Process.Start(start);
        }
    }
}

此類將在Javascript中公開。稍后您將看到,它是非常基本的,顯示了chrome瀏覽器的dev工具,並啟動了cmd.exe進程。

現在我們的InitializeChromium函數應該如下所示:

public void InitializeChromium()
{
    CefSettings settings = new CefSettings();

    // Note that if you get an error or a white screen, you may be doing something wrong !
    // Try to load a local file that you're sure that exists and give the complete path instead to test
    // for example, replace page with a direct path instead :
    // String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";

    String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);
    //String page = @"C:\Users\SDkCarlos\Desktop\artyom-HOMEPAGE\index.html";

    if (!File.Exists(page))
    {
        MessageBox.Show("Error The html file doesn't exists : "+page);
    }
    
    // Initialize cef with the provided settings
    Cef.Initialize(settings);
    // Create a browser component
    chromeBrowser = new ChromiumWebBrowser(page);
       
    // Add it to the form and fill it to the form window.
    this.Controls.Add(chromeBrowser);
    chromeBrowser.Dock = DockStyle.Fill;
    
    // Allow the use of local resources in the browser
    BrowserSettings browserSettings = new BrowserSettings();
    browserSettings.FileAccessFromFileUrls = CefState.Enabled;
    browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
    chromeBrowser.BrowserSettings = browserSettings;
}

我們使用File.Exists方法來查看Providen路徑是否存在,否則您在前面的步驟中做錯了什么。

現在,我們只需要執行它並在InitializeComponent函數中公開該類:

public Form1()
{
    InitializeComponent();
    // Start the browser after initialize global component
    InitializeChromium();
    // Register an object in javascript named "cefCustomObject" with function of the CefCustomObject class :3
    chromeBrowser.RegisterJsObject("cefCustomObject", new CefCustomObject(chromeBrowser, this));
}
  • 如果您的項目與主磁盤位於不同的硬盤驅動器中,請當心,因為在開發中,其他路徑而不是(C://)很有可能失敗。
  • 請注意,將RegisterJsObject功能注冊為一個全局對象,該類以Providen名稱作為第一個參數。在這種情況下,Javascript中的全局對象將為cefCustomObject

而已 !現在您只需要證明該應用程序,現在的主類應該與之前的所有代碼看起來類似:

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.Runtime.InteropServices;

namespace embebbedChromium
{
    public partial class Form1 : Form
    {
        public ChromiumWebBrowser chromeBrowser;

        public Form1()
        {
            InitializeComponent();
            // Start the browser after initialize global component
            InitializeChromium();
            // Register an object in javascript named "cefCustomObject" with function of the CefCustomObject class :3
            chromeBrowser.RegisterJsObject("cefCustomObject", new CefCustomObject(chromeBrowser, this));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chromeBrowser.ShowDevTools();
        }

        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();

            // Note that if you get an error or a white screen, you may be doing something wrong !
            // Try to load a local file that you're sure that exists and give the complete path instead to test
            // for example, replace page with a direct path instead :
            // String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";

            String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);
            //String page = @"C:\Users\SDkCarlos\Desktop\artyom-HOMEPAGE\index.html";

            if (!File.Exists(page))
            {
                MessageBox.Show("Error The html file doesn't exists : "+page);
            }
            
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            chromeBrowser = new ChromiumWebBrowser(page);
               
            // Add it to the form and fill it to the form window.
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;
            
            // Allow the use of local resources in the browser
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.FileAccessFromFileUrls = CefState.Enabled;
            browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
            chromeBrowser.BrowserSettings = browserSettings;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }
    }
}

如前所述,要處理Javascript部分,  RegisterJsObject函數將創建一個名稱為Providen作為第一個參數的對象。在index.html文件中,我們將創建以下按鈕,這些按鈕使用javascript執行本機功能:

<button class="btn btn-info" onclick="cefCustomObject.showDevTools();">Open Chrome Dev Tools</button>
<button class="btn btn-primary" onclick="cefCustomObject.opencmd();">Open cmd.exe</button>

記住要尊重“ camelCase”,C#中的方法需要以lowerCase開頭,並遵守camelCase規則(無下划線_),如該類所示。

如您所見,借助CefSharp,一切都是雙向的,您可以輕松地從c#處理javascript或從javascript處理c#。

現在啟動您的應用程序,並在Windows中將HTML控件用作圖形用戶界面!

Chrome最終HTML UI

如果您在javascript中看到已注冊的類,則將看到具有所有已注冊方法和功能的對象作為本機代碼(equalsgetHashCode並且toString會自動添加)。

向C#注冊的Javascript對象

 


免責聲明!

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



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