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

C# 在 WebBrowser 控件中使用 SendMessage 模擬滑鼠點擊

     編輯:ASP.NET 基礎

需求背景

WinForms WebBrowser 控件無直接模擬點擊方法,需透過 Windows API SendMessage 向內部 IE 視窗發送 WM_LBUTTONDOWN/WM_LBUTTONUP。

完整代碼

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace BrowserMouseClick
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://www.example.com");
        }

        private void btnMouseClick_Click(object sender, EventArgs e)
        {
            int x = 100, y = 80; // 點擊座標
            IntPtr handle = webBrowser1.Handle;
            var sb = new StringBuilder(100);

            // 向下尋找 Internet Explorer_Server 類別視窗
            while (sb.ToString() != "Internet Explorer_Server")
            {
                handle = GetWindow(handle, 5); // GW_CHILD = 5
                GetClassName(handle, sb, sb.Capacity);
            }

            IntPtr lParam = (IntPtr)((y << 16) | x);
            IntPtr wParam = IntPtr.Zero;
            const uint WM_LBUTTONDOWN = 0x201;
            const uint WM_LBUTTONUP = 0x202;

            SendMessage(handle, WM_LBUTTONDOWN, wParam, lParam);
            SendMessage(handle, WM_LBUTTONUP, wParam, lParam);
        }
    }
}

關鍵點解析

API用途
GetWindow(hWnd, 5)取得子視窗句柄 (GW_CHILD)
GetClassName確認視窗類別名稱為 "Internet Explorer_Server"
lParam = (y << 16) | x將 X、Y 座標打包
WM_LBUTTONDOWN/UP模擬滑鼠左鍵按下/放開

注意事項

  • 座標為控件客戶區相對位置,非螢幕座標。
  • 若頁面有框架,可能需遞迴尋找正確的子視窗。
  • 僅適用於 IE 核心模式;Edge/WebView2 需另行處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved