I have the following code that detects the enter key press and works ok. however, if you click a button on the form then it stops working i.e. the button pressed now has focus and enter press goes straight to that button.
private void Form1_Load(object sender, EventArgs e)
{
KeyPreview = true;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed");
}
}
I have tried the following with no success;
- Using forms PreviewKeyEvent instead of keyUp
- Using forms KeyDown instead of KeyUp
- Creating a button that is selected as the form's 'AcceptButton'
My workaround is to create a button that the form 'selects' on load, which will be clicked on entering. Then to have a timer running to maintain focus on that button in case any others are selected. This seems a bit of a shoddy solution.
Any ideas would be appreciated. Seems like I am missing something obvious.
Phil