C# 模拟Windows键盘事件

发送winform-Key值键盘消息

1.发送键盘消息

1         [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
2         public static extern void keybd_event(
3             byte bVk,    //虚拟键值
4             byte bScan,// 一般为0
5             int dwFlags,  //这里是整数类型  0 为按下,2为释放
6             int dwExtraInfo  //这里是整数类型 一般情况下设成为 0
7         );

使用系统dll下的keybd_event,来发送键盘消息。

dwFlags:0为按下,2为释放

所以发送一个组合键:LeftCtrl+LeftShift+Divide,需要如下操作:

  • 组合键,每个键都需要发送
  • 按键有按下和抬起操作。如果只发送按下,表示按键长按。。。
1     keybd_event((byte)Keys.LControlKey, 0, 0, 0);
2     keybd_event((byte)Keys.LShiftKey, 0, 0, 0);
3     keybd_event((byte)Keys.Divide, 0, 0, 0);
4     keybd_event((byte)Keys.Divide, 0, 2, 0);
5     keybd_event((byte)Keys.LShiftKey, 0, 2, 0);
6     keybd_event((byte)Keys.LControlKey, 0, 2, 0);

参考资料:

keybd_event模拟对照表以及用法.

2.接收键盘消息

1     private void UIElement_OnPreviewKeyDown(object sender, KeyEventArgs e)
2     {
3         OutputTextBox.Text += string.IsNullOrEmpty(OutputTextBox.Text) ? e.Key.ToString() : "
" + e.Key.ToString();
4         OutputTextBox.SelectionStart = OutputTextBox.Text.Length + 1;
5     }

发送WPF-Key值键盘消息

如果嫌上面的user32调用麻烦,nuget上已经有一个封装整套键盘事件的源InputSimulator,它很强大,可以做键盘、鼠标、输入发送操作。

InputSimulator,发送的是System.Windows.Input.Key值。

如下,发送的是ctrl+alt+multipy组合键:

1     var ctrlAndAlt = new List<VirtualKeyCode>() { VirtualKeyCode.LCONTROL, VirtualKeyCode.LMENU };
2     InputSimulator inputSimulator = new InputSimulator();
3     inputSimulator.Keyboard.ModifiedKeyStroke(ctrlAndAlt, VirtualKeyCode.MULTIPLY);

 WPF-Winform键值类型转换

WPF提供了一个可以互转键盘键值类型的类KeyInterop,所以通过以下的俩个方法实现键值转换,wpf键值也可以通过user32发送。

    var virtualKeyIntValue = KeyInterop.VirtualKeyFromKey(wpfKey)

    var wpfKey = KeyInterop.KeyFromVirtualKey((int)winformKey)

 Demo:https://github.com/Kybs0/KeyBoardEventDemo

原文地址:https://www.cnblogs.com/kybs0/p/11507718.html