0


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

  1. 下载Microsoft.Web.WebView2

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

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

  4. 写如下代码:

//窗体装载事件
private void ProductChartForm_Load(object sender, EventArgs e)
{
    this.webView2_main.CoreWebView2InitializationCompleted += new EventHandler<Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs>(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}')");
 }
  1. 这样就可以使用了。可以用C#做一个框架,里面用webview2调用Html。利用css可以做出比较漂亮的界面。我这里使用了echarts 做了一些图表。
标签: c#

本文转载自: https://blog.csdn.net/zhang_peisheng/article/details/133556028
版权归原作者 花咔咔 所有, 如有侵权,请联系我们删除。

“C# 如何使用 webview2 调用本地html文件”的评论:

还没有评论