views:

88

answers:

3

I have a strange one.

Create a new form. Then add the following function :

 protected override void OnLoad ( EventArgs e )
 {

  if ( _goWrong )
  {
   this.MinimumSize = new System.Drawing.Size ( 420, 161 );
   this.Font = new Font ( "Tahoma", this.Font.Size, this.Font.Style );
  }

  TextBox box = new TextBox ();
  this.Controls.Add ( box );

 }
  • If _goWrong is false, so we dont set the minimum size or change the font, when I open up the form the focus is on the newly created TextBox. The user can then happily type away..

  • If _goWrong is true, so we do set the minimum size and change the font, when the form is opened, the focus is nowhere to be seen!

What the hell is going on? Why would this have any effect on the focus? Am I missing something here?

This is in .Net 2.0.5

Thanks

+1  A: 

When going wrong, setting the minimum form size steals the focus (goes to the form). Changing the font has no effect. This is weird, however...

UPDATE:

Setting the focus in OnLoad works though (box.Select()).

Sorin Comanescu
Darn it. Yup using Select works in this little test app, but doesnt do it in our main app, which is a lot more complex..
Mongus Pong
So I still need to understand fully whats going on before I can move forward!
Mongus Pong
A: 

Do this (if I read your problem correctly):

protected override void OnLoad ( EventArgs e )
        {

                if ( _goWrong )
                {
                        this.MinimumSize = new System.Drawing.Size ( 420, 161 );
                        this.Font = new Font ( "Tahoma", this.Font.Size, this.Font.Style );
                }

                TextBox box = new TextBox ();                    
                this.Controls.Add ( box );
                box.Focus();//<----Add this line here and the textbox will get focus.
        }
Sergio Tapia
I have tried this. It makes no difference.As I said before, I can put a timer on the form and call Focus in the Timer tick. That fixes it. But it is not a satisfactory solution, and I want to know why this would go wrong..
Mongus Pong
+1  A: 

Okay, I tried this out, and came up with a few observations:

  • It's the MinimumSize property set that's the culprit
  • The code works fine when the TextBox is placed on the form directly instead of created dynamically
  • The code works if the TextBox is created before the MinimumSize is set

I can't explain why this is happening (I thought it might be an issue with the tab order -- it's not), but this should give an idea for a workaround.

Jon Seigel