A tutorial on how to embed a Web browser using Cefsharp in the WPF framework

Source: Internet
Author: User
Tags html page versions visibility xmlns


First describes the Cefsharp embedded browser, which is based on a Google browser component that we can use in Wpf/winform client software. Cefsharp code is hosted on GitHub,. NET (WPF and Windows Forms) bindings for the Chromium Embedded Framework.

The latest version of Cefsharp is version 41.0 and it is recommended that you use CEFSHARP.WPF 1.25.7 and previous versions if your client software needs to support the win XP operating system. Specific content can be obtained from the NuGet. In the new version of Cefsharp, support for the Win XP system has been canceled.

Specific implementation: (first refer to Cefsharp.dll,cefsharp.wpf.dll to place Icudt.dll,libcef.dll these two DLLs in Bin/debug or bin/release directory)
first creates a UserControl and inherits the IRequestHandler interface, the code is as follows:


<usercontrol x:class= "Embeddedwebbrowsersolution.webpageviewer"       
       xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x= "http:// Schemas.microsoft.com/winfx/2006/xaml "              xmlns:mc= "http://schemas.openxmlformats.org/markup-compatibility/2006"                 xmlns:d= "http://schemas.microsoft.com/expression/blend/ 2008 "               xmlns:local=" Clr-namespace:embeddedwebbrowsersolution "              xmlns:uc= "Clr-namespace:embeddedwebbrowsersolution"               mc:ignorabLe= "D"                d:designheight= "300"  d:designwidth= "    <grid x:name=" > "Maingrid" >          <uc:maskloading x:name= "maskloading"/>     </ Grid> </UserControl>


Public partial class webpageviewer : usercontrol, irequesthandler {  
  private WebView _view;     public webpageviewer (string url)     {   
     initializecomponent ();         cef. Initialize (new settings { logseverity = logseverity.disable, packloadingdisabled
 = true });         BrowserSettings browserSetting = new  Browsersettings { applicationcachedisabled = true, pagecachedisabled = true
 };         _view = new webview (String. empty, browsersetting)         {             address = url, &NBSp;           requesthandler = this,              background = brushes.white  
       };         _view.
loadcompleted += _view_loadcompleted;
        maingrid.children.insert (0, _view); &NBSP;&NBSP;&NBSP;&NBSP}     private void _view_loadcompleted (Object sender ,  loadcompletedeventargs url)     {         dispatcher.begininvoke (New action ()  =>           {            maskloading.visibility =
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}));     }      public void view (string url)     {         if (_view. isbrowserinitialized)         {             _view.
visibility = visibility.hidden;             maskLoading.Visibility = 
visibility.visible;             _view.
Load (URL); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}    &nbsp}      #region  irequesthandler     public bool getauthcredentials (IWebBrowser browser , bool isproxy, string host, int port, string realm, string  Scheme, ref string username, ref string password)     {         return false; &NBSP;&NBSP;&NBSP;&NBSP}     public bool getdownloadhandler (IWebBrowser  browser, string mimetype, string filename, long contentlength, ref  Idownloadhandler handler)     {        return
 true; &NBSP;&NBSP;&NBSP;&NBSP}     public bool onbeforebrowse (IWebBrowser browser ,  irequest request, navigationtype naigationvtype, bool isredirect)      {        return false;     }      public bool onbeforeresourceload (iwebbrowser browser, irequestresponse  requestresponse)     {        return 
False     }     p Ublic void onresourceresponse (iwebbrowser browser, string url, int status ,  string statustext, string mimetype, webheadercollection headers)      {             }      #endregion}

Next, hosted on MainWindow,


<Grid>     <DockPanel>         < stackpanel dockpanel.dock= "Top"  orientation= "Horizontal" >              <textblock text= "Address:"  margin= "5"/>              <textbox x:name= "txtAddress"  Width= "350"  margin= "5"/>             <Button  Content= "Go"  margin= "5"  click= "Ongoclick"  isdefault= "True"/>          </StackPanel>         <grid x:name= " Maingrid ">                       </Grid>     </DockPanel> </Grid> code:private  Void ongocliCK (object sender, routedeventargs e) {    string url = 
Txtaddress.text;     if  (!string. Isnullorwhitespace (URL))     {        webpageviewer
 viewer = new webpageviewer (URL);
        maingrid.children.insert (0,viewer); &NBSP;&NBSP;&NBSP;&NBSP}}

Note that the project platform target should be set to X86.

Operation Effect:

Here, an example of using Cefsharp to host a Web page is complete.

Compared to the WPF built-in Webbrowser,cefsharp, it is much more convenient to handle JS back-fall than WebBrowser. Take a look at the following example:

We have such an HTML page:

<! DOCTYPE html>

Add a class, called: Callbackobjectforjs

public class Callbackobjectforjs
void ShowMessage (String msg)
MessageBox.Show (m    SG);

Note that the name of this method must be lowercase.

To transform the Webpageviewer class, after the construction webview, register a JS object,

... public webpageviewer (string url) {    initializecomponent ();      cef. Initialize (new settings { logseverity = logseverity.disable, packloadingdisabled
 = true });     BrowserSettings browserSetting = new BrowserSettings { 
applicationcachedisabled = true, pagecachedisabled = true };     _view = new webview (String. empty, browsersetting)     {        address  = url,         requesthandler = this,   
      background = brushes.white     };     _view.
Registerjsobject ("Callbackobj",  new callbackobjectforjs ());     _view. loadcompleted += _view_LoadCompleted;
    maingrid.children.insert (0, _view); }   //...

The operation effect is as follows:

In this way, we can very well implement the interaction between Web pages and client programs.

Embed a Chrome browser in a. NET program using Cefsharp

Sometimes, we need to embed the Web browser in the program, in fact, the. Net framework itself provides the WebBrowser control, itself this is the easiest to use the solution, but do not know what the reason, the control in the Web browsing some inexplicable cotton, Sometimes it can even reach a few seconds, seriously affecting the experience.

At this time, we can consider using a Third-party browser to replace the system's WebBrowser, the common solution is to use the version of the Dili Chrome,chrome itself provided for third-party programs embedded chromium Embedded Framework (CEF), But this is the C + + interface, in the. NET program to use or there is a certain amount of work. However, there are already some open source projects to complete this package, one of the best is the CEFSHARP,WPF and WinForm encapsulation is implemented, this article simply describes how to use the WPF program Cefsharp to embed the Chrome browser.


The installation process is very simple, as long as the use of NuGet installation CEFSHARP.WPF can be.

Pm> Install-package CEFSHARP.WPF

The installation process itself is more routine, it is worth mentioning, however, that this package is very large, because of the integration of the x86 and x64 versions, the entire package (plus several dependent packages) reached more than 200 MB, based on well-known reasons, and NuGet access has been not smooth, and sometimes the whole process is very long, Be patient enough and have a character.

To modify the compilation options:

Because Chrome is a native program, the current cefsharp can not do 32-bit and 64-bit automatic recognition, can not use the default ANYCPU compilation options, need to modify the Configuration Manager, change to x86 or x64 just line.


The use of the process is relatively simple, directly using the following code can be.

private void Mainwindow_loaded (object sender, RoutedEventArgs e)
var setting = new Cefsharp.cefsettings ();
CefSharp.Cef.Initialize (setting, True, false);

var webview = new CefSharp.Wpf.ChromiumWebBrowser ();
This. Content = WebView;

webview.address = "http://www.cnblogs.com/TianFang/";

We can see the next action before using the Chrome control:

var setting = new Cefsharp.cefsettings ();
CefSharp.Cef.Initialize (setting, True, false);

This setting variable is where the chrome's global settings are stored, and when you need to set it up, you just need to modify it. For example, to modify the cache directory, you only need the following settings:

var setting = new Cefsharp.cefsettings ()
CachePath = directory.getcurrentdirectory () + @ "\cache",

In addition, some settings are passed through the startup parameters, which are stored in the Cefcommandlineargs member and passed in as a string. For example, to add a proxy server to a chrome program, you can modify the following:

Setting. Cefcommandlineargs.add ("--proxy-server", "");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.