8,750
社区成员
发帖
与我相关
我的任务
分享
开发环境:WPF 、 Windows 11系统 、Visual Studio 2022 (管理员启动)
想实现一个功能:通过WPF调用user32,模拟鼠标点击,目前通过SetCursorPos和mouse_event函数已经可以实现,鼠标会移动到对应坐标不太友好,想用SendInput实现静默点击。
遇到的问题:SendInput实现静默点击不起作用
public class MouseSimulator
{
// 鼠标事件类型
[Flags]
public enum MouseEventFlags
{
LeftDown = 0x0002,
LeftUp = 0x0004,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
RightDown = 0x0008,
RightUp = 0x0010,
Wheel = 0x0800,
XDown = 0x0080,
XUp = 0x0100
}
// 定义鼠标输入结构体
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public MouseEventFlags dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
// 定义输入结构体
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public int type;
[FieldOffset(4)]
public MOUSEINPUT mi;
}
// 导入SendInput函数
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray)] INPUT[] pInputs, int cbSize);
// 鼠标模拟单击方法
public static void SimulateMouseClick(int x, int y)
{
// 设置鼠标坐标
MOUSEINPUT mouseInput = new MOUSEINPUT
{
dx = x,
dy = y
};
// 设置鼠标点击事件
mouseInput.dwFlags = MouseEventFlags.LeftDown;
INPUT inputDown = new INPUT
{
type = 0,
mi = mouseInput
};
mouseInput.dwFlags = MouseEventFlags.LeftUp;
INPUT inputUp = new INPUT
{
type = 0,
mi = mouseInput
};
// 模拟鼠标点击事件
INPUT[] inputs = new INPUT[] { inputDown, inputUp };
SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
}
}