KeyPreview not handling KeyUp Event before control does

548 views Asked by At

I have a form, myForm, which has KeyPreview set to true.

The idea is that I want to capture CTRL-Enter and fire the submit button of the form, no matter what textbox (or other control) that may have focus.

So I set up this method:

private void myForm_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.Enter)
    {
        btnCommit_Click(sender, new EventArgs()); 
    }
}

Which does exactly what it says. The problem is, the enter key stroke is also fired in the textbox that had focus, so the textbox now has a line break right in the middle of a word or wherever the cursor was. According to the MSDN docs:

When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus.

This is unfortunatly NOT TRUE, I have verified by stepping through the code that the textbox does indeed show the new line break BEFORE the myForm_KeyUp code gets fired.

I have tried adding both

e.Handled = true;

and

e.SuppressKeyPress = true;

To no effect, as the textbox already shows the linebreak.

Any ideas? Am I missing something?

2

There are 2 answers

0
Neil N On BEST ANSWER

So this should have been a no brainer. I typed all that out only to realize I should have been handling KeyDown instead of KeyUp. KeyUp obviously fires AFTER the KeyDown of the TextBox, even though it does fire before the KeyUp of the TextBox.

0
Hans Passant On

You should override OnProcessCmdKey() instead. It runs early, ensuring that no control could steal the keystroke.