KeyUp event routing issues in Windows Forms.

G

Guest

I believe I have found a bug in how keyboard events are routed in Windows
Forms. I am not sure if this is a bug or how to work around it.

MessageBoxes (MessageBox.Show) that are opened over top of a form end up
routing their KeyUp events to the active control beneath the messagebox.

For example, if I have a TextBox control focused on a form, and I open a
message box, pressing "enter" to close the message box causes the TextBox
control to receive a KeyUp event for the enter that was pressed in the dialog!

It's almost as though the message is getting routed to the incorrect location.

To reproduce this problem, create a new Windows Application (C#) project in
Visual Studio 2003 (.NET 1.1. The issue occurs in the service pack edition as
well).

Drop a TextBox control onto the form's canvas from the toolbox. The bug
occurs in any control that can receive focus, but in this case I will use a
TextBox.

Add a MouseUp event handler to the textbox with the following code:
private void textBox1_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
MessageBox.Show("The textbox was clicked. Pressing 'enter' on this
dialog will cause the keyboard event to be incorrectly routed to the text
box.");
}

Then add a KeyUp event handler to the textbox with the following code:
private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs
e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("An Enter KeyUp event was received by the text box.
If you pressed enter to close the dialog, this message was incorrectly
received! Pressing enter again on this messagebox will cause an endless
loop!");
}
}

Save the project and then run the application. Click on the textbox to cause
the messagebox to appear, then press the enter key while the messagebox is
focused. The KeyUp event was routed to the wrong location, possibly causing
undesired behavior!

I noticed this bug with we were writing "ESC" key handling code in our
application to close documents. A messagebox would appear, and if the user
pressed "ESC" to close the messagebox, the ESC key event would get routed to
the document, which would cause it to close - definately not correct
behavior! :(

I don't have the KeyPreview property enabled on the form. Is there any work
around for this? KeyPress and KeyDown don't get executed however. I suppose I
could move the code into the KeyDown event.
 

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