WinForm 模拟点击其他软件按钮:步骤、代码示例及注意事项
WinForm可以通过模拟Windows消息实现模拟点击别的软件的按钮。具体步骤如下:
-
找到需要模拟点击的按钮的句柄,可以使用FindWindow或FindWindowEx函数来查找。
-
使用SendMessage或PostMessage函数发送BM_CLICK消息给按钮窗口句柄,模拟点击操作。
示例代码如下:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
const uint BM_CLICK = 0x00F5;
// 查找父窗口句柄
IntPtr parentHwnd = FindWindow(null, '父窗口标题');
// 查找子窗口句柄
IntPtr childHwnd = FindWindowEx(parentHwnd, IntPtr.Zero, null, '按钮标题');
// 发送点击消息
SendMessage(childHwnd, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
需要注意的是,模拟点击操作可能会对被操作的程序产生影响,建议在合适的场景下使用。
原文地址: https://www.cveoy.top/t/topic/lC1v 著作权归作者所有。请勿转载和采集!