Winform 嵌入html,数据交互,将JS中的数据等传给winform
点击浏览器中的按钮,触发 Winform 中的方法
https://github.com/cefsharp/CefSharp
C# Code
namespace SharpBrowser
{
public partial class WebViewTest : Form
{
public ChromiumWebBrowser chromeBrowser;
public WebViewTest()
{
InitializeComponent();
InitializeChromium();
}
//初始化浏览器并启动
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser("http://172.16.0.66/C/");
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
CefSharpSettings.WcfEnabled = true;
chromeBrowser.JavascriptObjectRepository.Register("jsObj", new SendCarBillPrint(), isAsync: false, options: BindingOptions.DefaultBinder);
// 将浏览器控件添加到当前Form窗体中
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill; //充满显示
}
//窗体关闭时,记得停止浏览器
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown(); //重要
}
}
class SendCarBillPrint
{
public string sendCode { set; get; }
public void invoke()
{
MessageBox.Show("JS 调用=>" + sendCode);
}
}
}
HTML Code
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div id="app">
<div>
<button id="bth">anwo</button>
hello chen
</div>
</div>
</body>
</html>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> -->
<script type="text/javascript" src="https://lib.baomitu.com/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript">
var jsObj;
$(document).ready(function () {
document.querySelector('#bth').onclick = function () {
if (jsObj == undefined)
{
alert("请使用客户端操作");
return;
}
jsObj.sendCode = 'abc';
jsObj.invoke();
}
})
</script>