Send keyboard messages
1 [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
2 public static extern void keybd_event(
3 byte bVk, //Virtual key value
4 byte bScan,// Generally 0
5 int dwFlags, //Here is an integer type 0 for pressing, 2 for releasing
6 int dwExtraInfo //Here is an integer type, generally set to 0
7 );
Use keybd_event under the system dll to send keyboard messages.
dwFlags: 0 means press, 2 means release
So send a key combination: LeftCtrl+LeftShift+Divide, you need the following operations:
- Combination keys, each key needs to be sent
- The keys have press and lift operations. If only a press is sent, it means a long press of the button. . .
1 keybd_event((byte)Keys.LControlKey, 0, 0, 0);
2 keybd_event((byte)Keys.LShiftKey, 0, 0, 0< /span>);
3 keybd_event((byte)Keys.Divide, 0, 0, 0< /span>);
4 keybd_event((byte)Keys.LControlKey, 0, 2, 0< /span>);
5 keybd_event((byte)Keys.LShiftKey, 0, 2, 0< /span>);
6 keybd_event((byte)Keys.Divide, 0, 2, 0< /span>);
Reference materials:
keybd_event simulation comparison table and usage.
Receive keyboard messages
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 span>;
5 }
Demo:https://github.com/Kybs0/KeyBoardEventDemo
1 [DllImport("user32 .dll", EntryPoint = "keybd_event", SetLastError = true)]
2 public static extern void keybd_event(
3 byte bVk, //Virtual key value
4 byte bScan,// Generally 0
5 int dwFlags, //Here is an integer type 0 for pressing, 2 for releasing
6 int dwExtraInfo //Here is an integer type, generally set to 0
7 );
1 keybd_event((byte)Keys.LControlKey, 0, 0, 0);
2 keybd_event((byte)Keys.LShiftKey, 0, 0, 0< /span>);
3 keybd_event((byte)Keys.Divide, 0, 0, 0< /span>);
4 keybd_event((byte)Keys.LControlKey, 0, 2, 0< /span>);
5 keybd_event((byte)Keys.LShiftKey, 0, 2, 0< /span>);
6 keybd_event((byte)Keys.Divide, 0, 2, 0< /span>);
1 private< /span> 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 span>;
5 }