WinForm `WebBrowser` 控制項 (IE ActiveX 封裝) **不直接暴露 DOM 滑鼠事件**。常見解法:在 `DocumentCompleted` 注入 JavaScript 監聽 `onclick`/`onmousedown`,觸發 `window.location.href = "cmd://event?..."` 導航,再在 `Navigating` 事件攔截自訂協定並取消導航,於 C# 處理邏輯。本文提供完整實作。
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`) |
`WebBrowser` 控制項屬舊技術 (IE 7/8/9/10/11 引擎),新專案**強烈建議遷移至 WebView2**。若必須維護舊系統,本文「DOM 注入 + 導航攔截」模式為捕獲滑鼠/鍵盤/自訂事件的標準解法。注意:`mshtml`/`SHDocVw` 為 COM 互通組件,部署時需確保目標機器已安裝 IE/Edge IE 模式。