C# 如何使用 webview2 调用本地html文件

慈云数据 2024-03-19 技术支持 179 0

1. 下载Microsoft.Web.WebView2

C# 如何使用 webview2 调用本地html文件
(图片来源网络,侵删)

2. 工具箱里面会出现一个webview2的控件

3. 把这个控件拖到窗体上

C# 如何使用 webview2 调用本地html文件
(图片来源网络,侵删)

4. 写如下代码:

//窗体装载事件
private void ProductChartForm_Load(object sender, EventArgs e)
{
    this.webView2_main.CoreWebView2InitializationCompleted += new EventHandler(this.WebView2InitializationCompleted);
}
//webview2装载完成监听
private void WebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
//本地路径
    string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
//本地html文件,可以把css和js文件导入
string filepath = currentPath + @"\html\index.html";
if (File.Exists(filepath))
{  //创建实例
    this.webView2_main.Source = new Uri(filepath);
    //导航完成监听
    webView2_main.NavigationCompleted += WebView_Navigated;
}
}
//导航完成后,可以写调用网页的js函数事件了。
 private void WebView_Navigated(object? sender, CoreWebView2NavigationCompletedEventArgs e)
 {
string str = "这里面是json格式的文本";
    //这里的task是网页js函数的返回值
     string task = await webView2_main.CoreWebView2.ExecuteScriptAsync($"loadBarChart('{str}')");
 }

5. 这样就可以使用了。可以用C#做一个框架,里面用webview2调用Html。利用css可以做出比较漂亮的界面。我这里使用了echarts 做了一些图表。

微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon