飞道的博客

使用 VebView2,在C#WinForm中显示前端效果,做到C#与js通讯

376人阅读  评论(0)

VebView2控件的使用

  1. 下载Microsoft Edge Can

  2. 新建winForm窗体项目

  3. 点击项目->管理NuGet程序包->浏览(WebView2)->安装

  4. 在窗体中添加TextBox(addressBar),Button(goButton),VebView2(webView)

  5. 更改webView控件的source属性,设置默认路径url:https://blog.csdn.net/Yueqin0512

  6. 给按钮添加点击事件

  7. 在Form1.cs添加引用using Microsoft.Web.WebView2.Core;,并添加如下代码

        public Form1()
        {
   
            InitializeComponent();
            this.Resize += new System.EventHandler(this.Form_Resize);

            webView.NavigationStarting += EnsureHttps;
            InitializeAsync();
        }

        private void Form_Resize(object sender, EventArgs e)
        {
   
            webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
            goButton.Left = this.ClientSize.Width - goButton.Width;
            addressBar.Width = goButton.Left - addressBar.Left;
        }

        private void goButton_Click(object sender, EventArgs e)
        {
   
            if (webView != null && webView.CoreWebView2 != null)
            {
   
                webView.CoreWebView2.Navigate(addressBar.Text);
            }
        }


        private void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
        {
   
            String uri = args.Uri;
            if (!uri.StartsWith("https://"))
            {
   
                webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
                args.Cancel = true;
            }
        }

        async void InitializeAsync()
        {
   
            await webView.EnsureCoreWebView2Async(null);
            webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;

            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
        }

        void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        {
   
            String uri = args.TryGetWebMessageAsString();
            addressBar.Text = uri;
            webView.CoreWebView2.PostWebMessageAsString(uri);
        }
  1. 运行程序,在textBox中显示当前网站的网址,Vebview显示当前网站,若在文本框中输入其他网址,点击按钮,也可直接跳转到相应网站。

使用 VebView2,在C#WinForm中显示前端效果,做到C#与js通讯

  1. 重复以上123步骤
  2. 在窗体中添加Button(Button1),VebView2(webView)
  3. 创建HTML文件(也可以使用Vue或者react,这里演示的是vue)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跑马灯效果</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <style>
	    body{
    background-color: lightpink;}
    </style>
</head>
<body>
    <div id="app">
        <input type="button" value="开始" @click="start">
        <input type="button" value="停止" @click="stop">
        <input type="button" value="Js TO C#" @click="JsTo">
        <h4>{
  { msg }}</h4>
    </div>

    <script>
        var vm = new Vue({
    
            el: '#app',
            data: {
    
                msg: '可以连续滚动的字体',
                intervalId: null 
            },
            methods:{
    
                start(){
    
                    if (this.intervalId != null) return;
                    this.intervalId = setInterval(() => {
    
                        this.msg = this.msg.substring(1) + this.msg.substring(0, 1)
                    }, 500)
                },
                stop(){
    
                    clearInterval(this.intervalId)
                    this.intervalId = null
                },
                JsTo(){
    
                    //触发上面注册的C#事件
                    window.chrome.webview.postMessage("Js TO C#: "+window.document.URL);
                }
            },
            mounted () {
    
                //监听message事件,C#的PostWebMessageAsString或PostWebMessageAsJson可以触发该事件
                window.chrome.webview.addEventListener('message', event => alert(event.data));
            }
        })
    </script>
</body>
</html>
  1. 在Form.cs中插入如下代码,路径需要修改
        public Form1()
        {
   
            InitializeComponent();

            InitializeAsync();
            this.webView.WebMessageReceived += WebView_WebMessageReceived;
        }

        async void InitializeAsync()
        {
   
            await webView.EnsureCoreWebView2Async(null);
            //文件路径
            this.webView.Source = new Uri(@"之前创建的HTML文件的路径");
        }
            
        private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
   
            MessageBox.Show(e.TryGetWebMessageAsString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
   
            this.webView.CoreWebView2.PostWebMessageAsString("C# to JS Message.");
        }
  1. 运行程序,效果如下

    点击按钮C# to JS
    点击JS to C#,显示文件的路径
    点击vebView中的按钮,html的效果依然呈现

转载:https://blog.csdn.net/Yueqin0512/article/details/115787248
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场