2

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;

  1. Using forms PreviewKeyEvent instead of keyUp
  2. Using forms KeyDown instead of KeyUp
  3. 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

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
Phil
  • 177
  • 1
  • 10
  • You could try to set focus to form - `this.Focus()` - after button's click event. – raidensan Oct 05 '18 at 10:21
  • Use the form key press event to handle the button key press event also – Dave Oct 05 '18 at 10:23
  • 1
    Try this question: https://stackoverflow.com/q/18291448/616304 It's a different button but the concept should be the same. – Stephen Wilson Oct 05 '18 at 10:25
  • Thanks all. this.Focus() or this.Select() doesn't work for the form. Only works on other objects in the form. @StephenWilson that code worked for PrintScn button. Do you know how I would modify to work with enter? I am not sure what this hex relates to "public const int WM_HOTKEY_MSG_ID = 0x0312;" i.e. what the code for the enter key is? – Phil Oct 05 '18 at 10:52
  • @StephenWilson How setting a global hook is good solution? Hooks are used when your app isn't the active one. In this case he needs to detect key press in his own form! – γηράσκω δ' αεί πολλά διδασκόμε Oct 05 '18 at 10:56
  • Actually, yes I tested with my form when minimised and another program open. The hook stops the key working in other programs which is no good. – Phil Oct 05 '18 at 11:03

1 Answers1

1

Override ProcessCmdKey:

protected override bool ProcessCmdKey( ref Message msg, Keys keyData ) {
    if( keyData == Keys.Enter ) {
        // Enter is pressed

        return true; //return true if you want to suppress the key.
    }

    return base.ProcessCmdKey( ref msg, keyData );
}