WebBrowser.Document 完成載入後,可透過 HtmlElement 取得 DOM 節點,並直接以 += 訂閱其 CLR 事件(如 Click、MouseDown),事件引數為 HtmlElementEventArgs。
using System;
using System.Windows.Forms;
namespace WindowsApplication5
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
}
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// 僅處理主文檔完成,忽略 iframe 等子框架
if (e.Url != webBrowser1.Url) return;
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("input"))
{
if (el.Name == "btnG") // 依 name/id/class 篩選目標元素
{
el.Click += Form1_Click; // 直接訂閱 CLR 事件
}
}
}
private void Form1_Click(object sender, HtmlElementEventArgs e)
{
MessageBox.Show("jinjazz pass - HTML 按鈕被點擊!");
}
}
}
e.Url == webBrowser1.Url 確保僅處理主文檔,避免 iframe 觸發多次。GetElementsByTagName, GetElementById, Document.All 等多種方式定位目標節點。HtmlElement 事件為標準 .NET 事件,支援 Click, MouseDown, KeyPress, Change 等,引數提供 MousePosition, KeyPressedCode 等資訊。webBrowser1.Document.InvokeScript("jsFunction") 執行 JavaScript,實現雙向通訊。.on() 再回呼 C#)。WebBrowser 底層為 IE ActiveX,渲染引擎較舊,現代 Web 應用建議遷移至 WebView2 (Edge Chromium)。透過 HtmlElement 事件模型,C# 可無縫接管網頁元素互動,是桌面應用內嵌 Web UI、自動化測試、爬蟲登入的基石技術。