WinForms 模拟鼠标点击其他软件 - InputSimulator 库使用指南
在 WinForms 中使用 InputSimulator 库模拟点击其他软件,可以通过以下步骤实现:
-
首先,需要在项目中引入 InputSimulator 库。
-
在需要模拟点击的事件中,创建一个 InputSimulator 对象,然后使用它的 Mouse 类模拟鼠标点击操作。
例如,下面的代码会在当前鼠标位置模拟一次左键点击:
using WindowsInput;
using WindowsInput.Native;
InputSimulator sim = new InputSimulator();
sim.Mouse.LeftButtonClick();
- 如果需要模拟点击其他应用程序的窗口,可以使用 Windows API 函数 FindWindow 和 SendMessage 来实现。
首先,使用 FindWindow 函数查找目标应用程序的窗口句柄,然后使用 SendMessage 函数发送鼠标点击消息。
例如,下面的代码会在 Notepad 应用程序的窗口中模拟一次左键点击:
using System.Runtime.InteropServices;
using WindowsInput;
using WindowsInput.Native;
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
InputSimulator sim = new InputSimulator();
IntPtr hwnd = FindWindow(null, "Untitled - Notepad");
PostMessage(hwnd, (uint)MouseEventFlags.LeftDown, IntPtr.Zero, IntPtr.Zero);
PostMessage(hwnd, (uint)MouseEventFlags.LeftUp, IntPtr.Zero, IntPtr.Zero);
需要注意的是,模拟点击其他应用程序的窗口可能会触发一些安全策略,如 UAC 提示框等。因此,在实际应用中需要格外注意。
原文地址: https://www.cveoy.top/t/topic/lEgR 著作权归作者所有。请勿转载和采集!