简体   繁体   中英

How do I read keyboard input on a Winform?

I've tried using the KeyUp and KeyDown events to read keyboard input but as soon as I place other controls on the Winform, the keys are not read. How do I make sure that the keys are read?

You could set KeyPreview = true on your form to catch keyboard events.

EDITED to let you understand:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A) 
        e.SuppressKeyPress = true;
}

Stupid sample that receives keyboard events and drop if A was pressed.
If focus is in a textbox, you'll see that text is written, but not A!!

EDITED AGAIN: I took this code from a VB.NET example.
In your usercontrol, use the text box's "Keypress" event to raise a "usercontrol event".
This code would be in your custom usercontrol:

'Declare the event
Event KeyPress(KeyAscii As Integer) 

Private Sub Text1_KeyPress(KeyAscii As Integer)
    RaiseEvent KeyPress(KeyAscii)
End Sub

See: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

set KeyPreview = true and your KeyUp and KeyDown will recognize all keyboard input.

As marco says set KeyPreview to true on your form to catch the key events in the entire form rather than just a control.

Use the KeyPress event ... KeyUp/Down are more for the framework than your code. KeyDown is good if you want to disable a key ... numeric only fields etc. In general KeyPress is the one you're after.

If you want to prevent the keystrokes from propogating to other controls set KeyPressEventArgs.Handled = true.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

Have you wired up the event handler?

MyForm.KeyDown += MyHandler;

You can also do this in the properties pane ... click the event icon ...

If you are looking for your Form itself to read the keyboard input, you already have your answer from other correspondents. I am adding this contribution for the possibility that you might want to add key handling to other controls or user controls on your form. My article Exploring Secrets of .NET Keystroke Handling published on DevX.com (alas, it does require a registration but it is free) gives you a comprehensive discussion on how and why all the various keyhandling hooks and events come into play. Furthermore, the article includes a "Keystroke Sandbox" utility for free download that actually lets you see which controls are receiving which key handling events.

Here is one illustration from the article to whet your appetite:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM