在 WinForms WebBrowser 控制項中即時顯示滑鼠座標,需搭配 Timer 元件輪詢游標位置。本文提供完整實作步驟與代碼。
WebBrowser (webBrowser1)。Timer (timer1),設定 Interval = 100 (毫秒)。ToolStripStatusLabel (toolStripStatusLabel1) 顯示座標。private void Form1_Load(object sender, EventArgs e) {
timer1.Start(); // 必須啟動 Timer
}
private void timer1_Tick(object sender, EventArgs e) {
// 判斷滑鼠是否在 WebBrowser 範圍內
if (webBrowser1.Bounds.Contains(this.PointToClient(Cursor.Position))) {
// 轉換為 WebBrowser 客戶區座標
Point pt = webBrowser1.PointToClient(Cursor.Position);
toolStripStatusLabel1.Text = $"X: {pt.X}, Y: {pt.Y}";
}
}
Cursor.Position:取得螢幕絕對座標。PointToClient:將螢幕座標轉換為控制項客戶區座標。Bounds.Contains:過濾滑鼠離開控制項時的雜訊。Timer:WebBrowser 無原生滑鼠移動事件,輪詢是最簡單方案。webBrowser1.Document.GetElementFromPoint(pt) 取得滑鼠下方 HTML 元素。此技巧適用於需在嵌入式瀏覽器中進行座標互動的 WinForms 應用。