Winform使用Webview2加载本地HTML页面并互相通信
往期目录
往期相关文章目录
专栏目录
本节目标
- 实现刷新按钮
- 点击
C# winform
按钮可以调用C# winform
代码显示到html上 - 点击
HTML
按钮可以调用C# winform
代码更改html按钮字体
核心代码
this.mainView2.ExecuteScriptAsync("调用方(发送消息..)");
- html->C#
-
- 确保mainView2的CoreWebView2异步初始化完成
this.mainView2.EnsureCoreWebView2Async(null);
-
- 在webview2的CoreWebView初始化之后设置属性
this.mainView2.CoreWebView2InitializationCompleted += (object sender, CoreWebView2InitializationCompletedEventArgs e)=>{
this.mainView2.CoreWebView2.Settings.IsScriptEnabled = true;
}
-
- 在coreWebview2完成时添加
WebMessageReceived
监听。如下代码。
this.mainView2.CoreWebView2InitializationCompleted += (object sender, CoreWebView2InitializationCompletedEventArgs e) => {
this.mainView2.CoreWebView2.Settings.IsScriptEnabled = true;
this.mainView2.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
};
private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
}
实现HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo2TextHTMl</title>
</head>
<script>
function winformToHtmlText(text){
document.querySelector('.test1').innerHTML=text;
}
function htmlToWinformText() {
alert("开始发送");
try {
chrome.webview.postMessage("创建按钮点击更改winform窗体上的按钮字体");
chrome.webview.postMessage({ b: "创建按钮点击更改winform窗体上的按钮字体" });
} catch (e) {
alert(e.message)
}
}
</script>
<body>
<div class="test1"></div>
<div>
<button onclick="htmlToWinformText()">创建按钮点击更改winform窗体上的按钮字体</button>
</div>
</body>
</html>
实现的窗体Demo2代码
public partial class Demo2 : Form
{
public Demo2()
{
InitializeComponent();
this.mainView2.EnsureCoreWebView2Async(null);
}
private async void Demo2_Load(object sender, EventArgs e)
{
string exePath = Application.StartupPath;
string relativePath = "../../HTML/Demo2.html";
string path = Path.GetFullPath(Path.Combine(exePath, relativePath));
this.mainView2.Source = new Uri(@"file:///" + path);
this.mainView2.CoreWebView2InitializationCompleted += (object sender2, CoreWebView2InitializationCompletedEventArgs e2) => {
this.mainView2.CoreWebView2.Settings.IsScriptEnabled = true;
this.mainView2.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
};
}
private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
this.butByHtmlChange.Text = e.WebMessageAsJson.ToString();
}
private void btnSendToHtml_Click(object sender, EventArgs e)
{
string text = "这是一段从窗体发送到HTMl的文字!";
this.mainView2.ExecuteScriptAsync($"winformToHtmlText('{text}')");
}
private void btnRefresh_Click(object sender, EventArgs e)
{
this.mainView2.Reload();
}
}
效果图
- 从窗体发送到HTMl的文字
- 从HTML 修改窗体按钮文字
往期相关文章目录
专栏目录