Mdi Bug - When Focus isn't enough

 
We discovered a problem with Mdi-style Windows.Forms applications with the .NET Framework 1.1 with and without SP 1. The problem causes incorrect handling of keyboard input by MdiClient windows.
 
To reproduce the problem we build a very simple forms application with a toolbar to open client windows. The client window has a text box and some buttons. We wired up a KeyDown handler to the textbox that checks for pressing the enter key while the cursor is in the text box. In the repro example simply shows a MessageBox when you pressed enter. The event handler works fine when you first open a client window.
 
 
 
 
However, when you click on any of the buttons, then open another client window (or change focus to another window in the Mdi Frame) and then put the cursor back into the text box and hit enter, the form will invoke the event handler for the button you clicked before you switched between child windows. It will no longer invoke the KeyPress handler that's hooked up to the textbox, like it did before we switched focus between the two children.
 
 
 
 
 
Trying to determine what's going on, we looked at a number of things. First we looked if it was a matter of the current focus on the form, but the Focused property is set to the TextBox when the handler for the button is executed.
 
Then we checked if the registered event handlers for the textbox were somehow getting messed up, but examining the event handlers with the code below showed that the events were still properly wired up. We also found that the sender object passed to the event handler is indeed the button, therefore we started looking for the problem in other areas.
 
The realized that the form acted as if it’s executing the event handler for the AcceptButton, but both AcceptButton properties, for the MdiChild and the main frame, were set to null.
 
We then concluded that it must be a bug in the Mdi Framework and sent it off to Microsoft. In the meantime, the only workaround we came up with was to add code to every button handler on the form to check the Focused property.
 
private void button2_Click(object sender, System.EventArgs e)
{
if( textBox1.Focused )
{
MessageBox.Show( "You should really call the text box event handler" );
 
}
else
{
MessageBox.Show( "Button 2" );
}
}
 
That workaround gets pretty tedious if you have lots of input controls on the form though. I'll post an update when I get a response from Microsoft.

5 Comments

Comments have been disabled for this content.