Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
Bildsoe Avatar asked Sep 23 '11 09:09

Bildsoe


2 Answers

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
like image 65
Marco Avatar answered Sep 24 '22 21:09

Marco


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.

like image 31
Thu marlo Avatar answered Sep 21 '22 21:09

Thu marlo