Reading keyboard key presses on WinForm

J

JDeats

I have a WinForm with a single command button in the middle, I have
added a KeyDown event handler to the form and the method for this is:

private void Form2_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
}

When I run the program and tap on the keyboard nothing happens, I set
a break-point and it is never reached. So I tried using the KeyPress
event instead and the same thing happens.

private void Form2_KeyPress(object sender, KeyPressEventArgs
e)
{
MessageBox.Show(e.KeyChar.ToString());
}

If I remove the button, both methods are called.... So it appears any
control placed on the page could have focus and prevent my general,
form-level keypress event handler from working as I would like. The
actual project I'm trying to incorporate this into could have many
controls on it, is there a general way to trap a key press by the user
regardless of which control on the form has focus, without adding a
keydown or keypress event handler for every control?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top