原文:.net中模拟键盘和鼠标操作

周银辉

其实SendKeys类提供的方法蛮好用的,可惜的是WPF中不能用了,说是WPF的消息循环方式改成了Dispatcher,所以直接调用System.Windows.Forms.SendKeys.Send()方法会报错. 不过没关系, 至少有use32的SendInput可用,通过P/Invoke方式,我们可以模拟键盘或鼠标操作.

定义是这样的:

[DllImport("user32.dll", SetLastError = true)]
internal static extern int SendInput(int nInputs, ref INPUT mi, int cbSize);
其中的INPUT结构表示一个键盘或鼠标操作:
[StructLayout(LayoutKind.Sequential)]
internal struct INPUT
{
internal int type;
internal INPUTUNION union;
};
[StructLayout(LayoutKind.Explicit)]
internal struct INPUTUNION
{
[FieldOffset(0)]
internal MOUSEINPUT mouseInput;
[FieldOffset(0)]
internal KEYBDINPUT keyboardInput;
};
[StructLayout(LayoutKind.Sequential)]
internal struct MOUSEINPUT
{
internal int dx;
internal int dy;
internal int mouseData;
internal int dwFlags;
internal int time;
internal IntPtr dwExtraInfo;
};
[StructLayout(LayoutKind.Sequential)]
internal struct KEYBDINPUT
{
internal short wVk;
internal short wScan;
internal int dwFlags;
internal int time;
internal IntPtr dwExtraInfo;
};
[Flags]
internal enum SendMouseInputFlags
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
Absolute = 0x8000,
};

关于这些方法或结构的定义在http://www.pinvoke.net/index.aspx 这个网站上可以查找得到(但不保证百分百靠谱)




下面这个代码文件做了一个很好的包装,可以下载后参考:


Simulation.zip




如何使用呢?


很简单, 要敲一个键, 比如回车:

Keyboard.Press(Key.Enter);
Keyboard.Release(Key.Enter);


要敲一个组合键:比如Alt+F4

Keyboard.Press(Key.LeftAlt);
Keyboard.Press(Key.F4);
Keyboard.Release(Key.LeftAlt);
Keyboard.Release(Key.F4);
要敲一段文字:

Keyboard.Type("notepad");
鼠标与之类似,比如:

Mouse.MoveTo(new System.Drawing.Point(x, y));
Mouse.Click(MouseButton.Right);
04-17 21:38