开发者

Dynamically created TextBox has no focus with MinimumSize and Font changed

开发者 https://www.devze.com 2022-12-09 17:13 出处:网络
I have a strange one. Create a new form. Then add the following function : protected override void OnLoad ( EventArgs e )

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.Con开发者_开发百科trols.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


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()).


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.


Please just try and use the following method. You need to override the OnShown method if you are not sure which minimise function is affecting you.

protected override void OnShown( EventArgs e ) 
{
    textbox1.Focus();
    base.OnShown( e ); 
}


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.
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消