C# 模拟鼠标操作
[Flags]
enum MouseEventFlag : uint //设置鼠标动作的键值
{
Move = 0x0001, //发生移动
LeftDown = 0x0002, //鼠标按下左键
LeftUp = 0x0004, //鼠标松开左键
RightDown = 0x0008, //鼠标按下右键
RightUp = 0x0010, //鼠标松开右键
MiddleDown = 0x0020, //鼠标按下中键
MiddleUp = 0x0040, //鼠标松开中键
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800, //鼠标轮被移动
VirtualDesk = 0x4000, //虚拟桌面
Absolute = 0x8000
}
//设置当前鼠标位置
[DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
//操作鼠标,第一个函数定义操作类型,包括移动,单击双击等
[DllImport("user32.dll")]
static extern bool mouse_event(MouseEventFlag flags, int x,int y,uint data,UIntPtr extraInfo);
[DllImport("USER32.DLL")]
public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public static void MouseClick()
{
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
public static void MouseDoubleClick()
{
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
Thread.Sleep(50);
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
public static void MouseRightClick()
{
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
public static void MouseDoubleRightClick()
{
mouse_event(MouseEventFlag.RightDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.RightUp, 0, 0, 0, UIntPtr.Zero);
Thread.Sleep(50);
mouse_event(MouseEventFlag.RightDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.RightUp, 0, 0, 0, UIntPtr.Zero);
}
public static void SetString(int x,int y,string input)
{
Thread.Sleep(50);
SetCursorPos(x, y);
Thread.Sleep(50);
MouseClick();
Thread.Sleep(50);
Clipboard.SetText(input);
keybd_event(0xA2, 0, 0, 0);
keybd_event(0x56, 0, 0, 0);
keybd_event(0x56, 0, 2, 0);
keybd_event(0xA2, 0, 2, 0);
}