/// <summary> /// 爲了使網頁可以與winForm交互 將 com 的可訪問性設置爲 true /// </summary> [System.Runtime.InteropServices.ComVisible(true)] public partial class Form1 : Form { /// <summary> /// 聲明變量 /// </summary> private CefSharp.CefSettings _settings; ChromiumWebBrowser _browser; public Form1() { try { InitializeComponent(); //初始化cefSharp AppLog.Info("cefSharp init ..."); _settings = new CefSharp.CefSettings(); CefSharp.Cef.Initialize(_settings); //下面設置,減小白屏的發生,此爲cefSharp的bug if (!_settings.MultiThreadedMessageLoop) { Application.Idle += (sender, e) => { Cef.DoMessageLoopWork(); }; } AppLog.Info("cefSharp init OK"); //設置窗口最大化,最頂端顯示 this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; this.TopMost = true; } catch (Exception ex) { AppLog.Error(ex.Message); } } private void Form1_Load(object sender, EventArgs e) { try { _browser = new ChromiumWebBrowser("../index.html"); _browser.RegisterJsObject("cefSharpBrower", new ScriptCallbackManager(), false); this.Controls.Add(_browser); } catch (Exception ex) { AppLog.Error(ex.Message); } } /// <summary> /// js調用方法類 /// </summary> [System.Runtime.InteropServices.ComVisible(true)] class ScriptCallbackManager { /// <summary> /// 關閉窗體 /// </summary> public void CloseWindow() { //退出程序,結束進程 Process.GetCurrentProcess().Kill(); } //方法1 public void Func1() { //具體實現 ... }
}
添加對cefSharp的引用javascript
using CefSharp; using CefSharp.WinForms;
頁面的調用和交互html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <style> body { background-color: cadetblue } </style> </head> <body> <div> <input value="關閉winform" type="button" id="btn_close" /> <input value="Func1" type="button" id="btn_calc" /> </div> <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> //關閉程序 $(function () { $("#btn_close").click(function () { cefSharpBrower.CloseWindow(); }); }); $(function () { $("#btn_calc").click(function () { cefSharpBrower.Func1(); }); }); </script> </body> </html>