1.引入CEfSharp newget包
2.把平台配置为X86或X64,any cpu不支持此控件
3.引入命名空间
using CefSharp; using CefSharp.WinForms;
4.初始化
Cef.Initialize(new CefSettings() { }); browser = new ChromiumWebBrowser("http://192.168.2.247:8083/Demo.html"); this.Controls.Add(browser); browser.Dock = DockStyle.Fill; browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged; ; browser.FrameLoadEnd += Browser_FrameLoadEnd;
5.后台访问前台代码
StringBuilder sb = new StringBuilder();//这里为js代码 sb.Append(" document.getElementById('drawlinetext').value = 'longlatstart:114.009162902832,22.9938430786133;longlatend:114.009162902832,22.9938411712646;color:lightgreen;message:<div>车长度为0米</br>距离南桥257.33</br>距离北桥256.92</div>'; var _elm = document.getElementById('drawline'); ; var _evt = document.createEvent('MouseEvents'); _evt.initEvent('click', true, true); _elm.dispatchEvent(_evt); "); browser.GetMainFrame().ExecuteJavaScriptAsync(sb.ToString()); browser.ExecuteScriptAsync("");//有时不好用不知道为啥
6.前台访问后台代码
(1)首先要设计一个前后台访问的通用类
public class BoundObject { public string MyProperty { get; set; } public void MyMethod(string ShowNickName, string html) { try { Console.WriteLine("我来响应前台的的事件"); } catch (Exception ex) { } } }
(2)把这个类作为中间媒介,前后端代码两边注册
前端
bound.myMethod(devicename, lng,lat);
后端
CefSharpSettings.LegacyJavascriptBindingEnabled = true;//设置允许使用js browser.RegisterJsObject("bound", new BoundObject());//bound必须为小写,bound相当于句柄,个人理解