C # simulates Windows Keyboard Event

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 }

share picture

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 }

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3054 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.