Bildsoe
Bildsoe

Reputation: 1340

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?

Upvotes: 6

Views: 37585

Answers (4)

Michael Sorens
Michael Sorens

Reputation: 36708

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:

enter image description here

Upvotes: 2

Marco
Marco

Reputation: 57573

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

Upvotes: 5

iDevForFun
iDevForFun

Reputation: 988

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 ...

Upvotes: 3

Thu marlo
Thu marlo

Reputation: 553

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.

Upvotes: 3

Related Questions