I have a C# winform, on which I have 1 button.
Now, when I run my application, the button gets focus automatically.
The problem is KeyPress
event of my form does not work because the button is focused.
I have tried this.Focus();
on FormLoad()
event, but still the KeyPress event is not working.
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
KeyDown is raised as soon as the user presses a key on the keyboard, while they're still holding it down. KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed.
Key Press EventThis event fires or executes whenever a user presses a key in the TextBox. You should understand some important points before we are entering into the actual example. e. Keychar is a property that stores the character pressed from the Keyboard.
The KeyPress event is used in the Windows Form when a user presses a character, space, or backspace key during the focus on the control, the KeyPress event occurs.
You need to override the ProcessCmdKey
method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.
Sample code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// look for the expected key
if (keyData == Keys.A)
{
// take some action
MessageBox.Show("The A key was pressed");
// eat the message to prevent it from being passed on
return true;
// (alternatively, return FALSE to allow the key event to be passed on)
}
// call the base class to handle other key events
return base.ProcessCmdKey(ref msg, keyData);
}
As for why this.Focus()
doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex
value. In this case, that's your button.
Try setting the Form's KeyPreview property to True.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With