.net中模拟键盘和鼠标操作[网络技术]
本文“.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 这个网站上可以查找得到(但不保证百分百靠谱)
若何利用呢?
很简单, 要敲一个键, 比方回车:
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);
以上是“.net中模拟键盘和鼠标操作[网络技术]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |