首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# WebBrowser 控制項捕獲滑鼠點擊事件 (DOM 注入 + 導航攔截)

     編輯:關於C#

WinForm `WebBrowser` 控制項 (IE ActiveX 封裝) **不直接暴露 DOM 滑鼠事件**。常見解法:在 `DocumentCompleted` 注入 JavaScript 監聽 `onclick`/`onmousedown`,觸發 `window.location.href = "cmd://event?..."` 導航,再在 `Navigating` 事件攔截自訂協定並取消導航,於 C# 處理邏輯。本文提供完整實作。

核心流程

  1. `WebBrowser.Navigating`:攔截 `cmd://` 協定,解析參數,`e.Cancel = true`。
  2. `WebBrowser.DocumentCompleted`:取得 `IHTMLDocument2`,`parentWindow.execScript` 注入 JS 事件綁定。
  3. JS 事件處理器:`window.location.href = 'cmd://onclick?x=100&y=200&tag=BUTTON'`。

完整程式碼

using System;
using System.Windows.Forms;
using mshtml;        // 參考 Microsoft.mshtml (COM)
using SHDocVw;       // 參考 SHDocVw (COM)

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

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigating += WebBrowser1_Navigating;
        // 需用 ActiveX 事件取得 DocumentCompleted 正確時機
        var ax = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
        ax.NavigateComplete2 += Ax_NavigateComplete2;

        webBrowser1.Navigate("https://www.example.com");
    }

    private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        if (e.Url.Scheme == "cmd")
        {
            e.Cancel = true; // 阻止實際導航
            // 解析 e.Url.Query 參數
            var query = System.Web.HttpUtility.ParseQueryString(e.Url.Query);
            string eventType = e.Url.Host; // onclick, onmousedown
            string x = query["x"], y = query["y"], tag = query["tag"];
            MessageBox.Show($"捕獲 {eventType}: ({x},{y}) 元素={tag}");
            // 這裡執行你的 C# 邏輯
        }
    }

    private void Ax_NavigateComplete2(object pDisp, ref object URL)
    {
        // 頁面載入完成 (含 iframe),注入 JS
        var doc = (mshtml.IHTMLDocument2)((SHDocVw.WebBrowser)pDisp).Document;
        if (doc == null) return;

        string script = @"
            document.onmousedown = function(e) {
                e = e || window.event;
                var target = e.target || e.srcElement;
                var url = 'cmd://onmousedown?x=' + e.clientX + '&y=' + e.clientY + '&tag=' + target.tagName;
                window.location.href = url;
            };
            document.onclick = function(e) {
                e = e || window.event;
                var target = e.target || e.srcElement;
                var url = 'cmd://onclick?x=' + e.clientX + '&y=' + e.clientY + '&tag=' + target.tagName;
                window.location.href = url;
            };
        ";
        doc.parentWindow.execScript(script, "JavaScript");
    }
}

關鍵點解析

項目說明
參考組件專案 → 加入參考 → COM → `Microsoft HTML Object Library` (mshtml)、`Microsoft Internet Controls` (SHDocVw)
`ActiveXInstance`取得底層 `SHDocVw.WebBrowser` 以掛 `NavigateComplete2` (比 `DocumentCompleted` 更可靠,含 iframe)
`execScript`IE 專用方法注入腳本,現代 Edge WebView2 請用 `ExecuteScriptAsync`
自訂協定 `cmd://`不與 http/https 衝突,易於識別攔截
座標系統`clientX/Y` 為視口座標;若需頁面座標用 `pageX/Y` (需考慮捲動)
安全性注入腳本僅在同源頁面生效;跨域 iframe 會拒絕存取 `document` (需 `try/catch`)

現代替代方案

  • WebView2 (Edge Chromium):`CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync` + `CoreWebView2.WebMessageReceived` (使用 `window.chrome.webview.postMessage`),效能、安全性、相容性全面優於 `WebBrowser`。
  • CefSharp / PuppeteerSharp:Chrome 嵌入方案,支援完整 CDP 協定。

結語

`WebBrowser` 控制項屬舊技術 (IE 7/8/9/10/11 引擎),新專案**強烈建議遷移至 WebView2**。若必須維護舊系統,本文「DOM 注入 + 導航攔截」模式為捕獲滑鼠/鍵盤/自訂事件的標準解法。注意:`mshtml`/`SHDocVw` 為 COM 互通組件,部署時需確保目標機器已安裝 IE/Edge IE 模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved