引入库:CefSharp.WinForms
using CefSharp; using CefSharp.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 大屏Win { public partial class Form1 : Form { static string url = System.Configuration.ConfigurationManager.AppSettings["url"].ToString();//从配置文件中读取要打开的url static ChromiumWebBrowser chromeBrowser = null; public Form1() { InitializeComponent(); try { CefSettings settings = new CefSettings(); settings.Locale = "zh-CN";//中文环境 settings.AcceptLanguageList = "zh-CN";//中文环境 settings.CachePath = System.IO.Directory.GetCurrentDirectory()+"\\cache";//设置缓存 Cef.Initialize(settings); chromeBrowser = new ChromiumWebBrowser(url); chromeBrowser.AddressChanged += Browser_AddressChanged;//监听地址变化 this.Controls.Add(chromeBrowser); chromeBrowser.Dock = DockStyle.Fill; //js和cs交互 chromeBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true; chromeBrowser.JavascriptObjectRepository.Register("yfcsobj", new yfcsobj(), isAsync: true, options: BindingOptions.DefaultBinder); chromeBrowser.ExecuteScriptAsync("refreshdata()");//c# 调用 js方法 } catch (Exception ex) { MessageBox.Show(ex.Message); Application.Exit(); } } private void Browser_AddressChanged(object sender, AddressChangedEventArgs e) { //MessageBox.Show(e.Address); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Cef.Shutdown(); } //监听键盘按键 private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.F12) { chromeBrowser.ShowDevTools();//打开调试模式 } } } }
public class yfcsobj { public void test(string msg) { MessageBox.Show(msg); } public void closeApp() { //彻底关闭进程 System.Environment.Exit(0); Application.Exit(); } }
html中使用
<html> <body> <button onclick="test()">test</button> <button onclick="test2()">test2</button> <script> function test(){ yfcsobj.test('test js'); } function test2(){ yfcsobj.closeApp(); } </script> </body> <html>