行业知识
C# 如何使用 webview2 调用本地html文件
2026-11-19 06:51:31
来源:互联网转载
1. 下载Microsoft.Web.WebView2
()2. 工具箱里面会出现一个webview2的控件
3. 把这个控件拖到窗体上
()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 做了一些图表。