c# - 如何检测 webview2 中的鼠标点击(c#/vb.net)

标签 c# vb.net webview2

我尝试获取 html 元素的点击事件。 使用我使用的 WebBrowser:

instance = Nothing
            instance = WebBrowser1.Document
            AddHandler instance.Click, AddressOf Document_Click

但是对于 Webview2,我没有找到好的做法。我必须注入(inject)一个javascript代码吗? 但是,我如何在 C# 或 Vb.net 应用程序中获取处理程序?

非常感谢。

这里是一个示例代码。我的函数中没有返回:WebView1_WebMessageReceived。为什么 ? 我想,我忘记了什么......

Imports System.IO
Imports Microsoft.Web.WebView2.Core
Imports Newtonsoft.Json


    Class MainWindow
        Public Sub New()
    
            InitializeComponent()
            InitializeSyncroComponent()
    
            ' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
    
        End Sub
    
        Structure JsonObject
            Public Key As String
            'Public Value As PointF
        End Structure
    
        Async Sub InitializeSyncroComponent()
            Await webview1.EnsureCoreWebView2Async
            webview1.CoreWebView2.Navigate("https://google.fr/")
        End Sub
    
        Private Sub WebView1_WebMessageReceived(ByVal sender As Object, ByVal e As Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs)
            Dim jsonObject As JsonObject = JsonConvert.DeserializeObject(Of JsonObject)(e.WebMessageAsJson)
    
            Select Case jsonObject.Key
                Case "contextmenu"
                    'contextMenuStrip1.Show(Point.Truncate(jsonObject.Value))
                Case "mousedown"
                    Stop
                    ' contextMenuStrip1.Hide()
            End Select
        End Sub
    
        Private Sub webview1_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles webview1.NavigationCompleted
            webview1.CoreWebView2.Settings.AreDefaultContextMenusEnabled = False
            Dim script As String = File.ReadAllText("d:\test_mouse.js")
            webview1.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script)
        End Sub
    End Class

脚本 Java:

document.addEventListener('mousedown', function (event)
{
    let jsonObject =
    {
        Key: 'mousedown',
        Value:
        {
            X: event.screenX,
            Y: event.screenY
        }
    };
    window.chrome.webview.postMessage(jsonObject);
});

编辑: 我发现我的错误... 真的不多!

我忘记了 webview 属性中的 WebMessageReceived 声明。

Webview Property

最佳答案

好的,我不知道 VB.Net,但你似乎能够翻译 C# 代码,所以我将尝试在 C# 中创建一个简单的工作解决方案:

首先,从 Nuget 下载 Microsoft.Web.WebView2Newtonsoft.Json 并安装到您的项目中(您可能已经这样做了)。

现在将 WebView2 放到表单上 - 然后在 Property Inspector 中:

  1. 将来源设置为:'https://google.fr/'

  2. 双击 CoreWebView2InitializationCompletedWebMessageReceived 事件以在您的代码中创建骨架。

现在将这段代码添加到 VB.Net:

using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public struct JsonObject
        {
            public string Key;
            public string Value;
        }

        private async void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            string script = File.ReadAllText("Mouse.js");
            await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
        }

        private void WebView21_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            JsonObject jsonObject = JsonConvert.DeserializeObject<JsonObject>(e.WebMessageAsJson);
            switch (jsonObject.Key)
            {
                case "click":
                    MessageBox.Show(jsonObject.Value);
                    break;

            }
        }
    }
}

现在在您的项目目录中创建一个 javascript 文件 ('Mouse.js'),选择该文件并在 Property Inspector 中选择 Copy to output directory 并选择:Copy if newer。这意味着,您的 VB 程序可以使用相对链接找到您的 javascript 文件。

现在将以下 javascript 粘贴到文件中:

document.addEventListener('click', function (event)
{
    let elem = event.target;
    let jsonObject =
    {
        Key: 'click',
        Value: elem.name || elem.id || elem.tagName || "Unkown"
    };
    window.chrome.webview.postMessage(jsonObject);
});

现在,当您运行它时,您应该会看到一个消息框,显示您单击的元素的 NameIDTag Name(在那个顺序)。

我使用 Key: 'click' 方法的原因是,当您稍后想要检测例如 MouseDown 时,您可以轻松添加该键 - 然后您可以检测两者(否则只能检测到一种事件)。

更新:

CoreWebView2Ready 事件更改为 CoreWebView2InitializationCompleted。这是该事件的新名称。它使用 CoreWebView2InitializationCompletedEventArgs作为 eventArgs。

关于c# - 如何检测 webview2 中的鼠标点击(c#/vb.net),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65354344/

相关文章:

vb.net - 更改 Visual Studio 中输出控制台的字体?

c# - 如何阻止 webview2 打开新的浏览器窗口而不是在浏览器内

c# - 启动保持事件状态的非阻塞线程的可能方法

c# - 使用 Matlab dll 时,在 Windows Store App 中的模块 mscorlib.dll 错误中找不到类型 System.ApplicationException

c# - 在数据库中插入空值

.net - WebView2 中的搜索功能

c++ - WebView2 中的新 Sec-* header

c# - CSV 导入(可变字段)

c# - HTTP Web 请求包装器/帮助器库

Vb.Net设置用户控件属性