CefSharp 是一款开源的使用.net平台基于谷歌的 封装浏览器组件,可用于winform wpf 。
chart.js 也是一款开源的图表展示组件。
我所作的就是使用这两个组件再winform上实时显示动态曲线。
涉及到的知识主要是winform和js交互。
private void frmMain_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; var settings = new CefSettings(); settings.Locale = "zh-CN"; //settings.CefCommandLineArgs.Add("--disable-web-security", "1");//关闭同源策略,允许跨域 //settings.CefCommandLineArgs.Add("ppapi-flash-version", "18.0.0.209");//PepperFlashmanifest.json中的version //settings.CefCommandLineArgs.Add("ppapi-flash-path", "PepperFlash\pepflashplayer.dll"); //settings.CefCommandLineArgs.Add("--enable-system-flash", "1");//使用系统flash /////允许浏览器地址栏使用文件地址 // settings.CefCommandLineArgs.Add("allow-access-from-files", "1"); // settings.CefCommandLineArgs.Add("allow-universal-access-from-files", "1"); settings.CefCommandLineArgs.Add("lang", "zh-CN"); Cef.Initialize(settings); String page = string.Format(@"{0}htmlindex.html", Application.StartupPath); if (!File.Exists(page)) { MessageBox.Show("Error The html file doesn't exists : " + page); } //地址用中文的,中文转换。 page = dealUrl(page); textBox1.Text = page; browser = new ChromiumWebBrowser(page); BrowserSettings browserSettings = new BrowserSettings(); browserSettings.FileAccessFromFileUrls = CefState.Enabled; browserSettings.UniversalAccessFromFileUrls = CefState.Enabled; browser.BrowserSettings = browserSettings; string txtHtml = string.Empty; toolStripContainer.ContentPanel.Controls.Add(browser); browser.Dock = DockStyle.Fill; browser.KeyboardHandler = new CEFKeyBoardHander(); th = new Thread(SendData); LstData = new List<int>(); //当浏览器解析对象的时候,去绑定js对象 browser.JavascriptObjectRepository.ResolveObject += (sender2, e2) => { var repo = e2.ObjectRepository; if (e2.ObjectName == "boundAsync") { BindingOptions bindingOptions = null; //Binding options is an optional param, defaults to null bindingOptions = BindingOptions.DefaultBinder; //Use the default binder to serialize values into complex objects //bindingOptions = new BindingOptions { Binder = new MyCustomBinder() }); //Specify a custom binder repo.NameConverter = null; //No CamelCase of Javascript Names //For backwards compatability reasons the default NameConverter doesn't change the case of the objects returned from methods calls. //https://github.com/cefsharp/CefSharp/issues/2442 //Use the new name converter to bound object method names and property names of returned objects converted to camelCase //这里这样写之后,js端调用的方法首字母要小写。 repo.NameConverter = new CamelCaseJavascriptNameConverter(); repo.Register("boundAsync", new JsObject(LstData), isAsync: true, options: bindingOptions); } }; //js对象绑定完成回调 browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender3, e3) => { var name = e3.ObjectName; Debug.WriteLine($"Object {e3.ObjectName} was bound successfully."); }; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试实时曲线</title> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js" integrity="sha512-b3xr4frvDIeyC3gqR1/iOi6T+m3pLlQyXNuvn5FiRrrKiMUJK3du2QqZbCywH6JxS5EOfW0DY0M6WwdXFbCBLQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> --> <script src="chart.js"></script> <style> </style> </head> <body style="margin-top:100px"> <h1><a href="https://www.cnblogs.com/HelloQLQ/">https://www.cnblogs.com/HelloQLQ/</a></h1> <!-- 展示canvas --> <div style=" 800px;"> <canvas id="myChart" style="800px; height:400px;" ></canvas> </div> <!--引入 chartjs--> <script type="text/javascript"> // 设置参数 var d1 = [65, 59, 80, 81, 56, 55, 40]; var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: d1 }, { label: "My Second dataset", backgroundColor: "rgb(151,187,205)", borderColor: "rgb(151,187,205)", pointBorderColor: "rgb(151,187,205)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgb(151,187,205)", data: [28, 48, 40, 19, 86, 27, 90] } ] }; // Get the context of the canvas element we want to select var ctx = document.getElementById("myChart").getContext("2d"); var myLineChart = new Chart(ctx, { type: 'line', data: data, // options: options }); (async function () { await CefSharp.BindObjectAsync("boundAsync"); })(); //d1[0] = 85; function Update() { boundAsync.sendData().then(function (str) { if (str != null) { var data1 = JSON.parse(str); console.log(data1); myLineChart.data.datasets[0].data = data1; // Would update the first dataset's value of 'March' to be 50 myLineChart.update(); } }); // console.log(str); } </script> </body> </html>
整个工程下载:
使用到的组件使用nuget安装。工程里没包含。nuget搜索 cefsharp 和newtonsoft