Thread: Setting a control to have startup focus

  1. #1
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401

    Setting a control to have startup focus

    I want a certain button on a form to start with the focus. I have tried the following:
    Code:
    private void MainFrm_Load(object sender, System.EventArgs e)
    {
    	button2.Focus();
    }
    
    public MainFrm()
    {
    	InitializeComponent();
    	button2.Focus();
    }
    However, it does not have any effect. The control with startup focus is always the first control in the tab order. What is a good way of doing this?
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  2. #2
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    Controls cannot be focused unless their owner window is visible. The window is not visible in the Load event or the class constructor.

    Here's an example of one method to get around this issue...
    Code:
    namespace YourApplication
    {
        class YourWindow : Form
        {
            public YourWindow()
            {
                InitializeComponent();
                this.HandleCreated += new EventHandler(YourWindow_HandleCreated);
            }
    
            void InitializeComponenet()
            {
                // ... stuff
            }
    
            void YourWindow_HandleCreated(object sender, EventArgs e)
            {
                this.BeginInvoke(new MethodInvoker(FocusFirst));
            }
    
            void FocusFirst()
            {
                this.SomeControl.Focus();
            }
        }
    }
    I use the Control.BeginInvoke() method, which can only be called after the window's handle has been created. The FocusFirst() method is called, and any control can be forced to focus, basically
    Last edited by BMJ; 09-19-2004 at 09:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Setting Focus in Dialog
    By keira in forum Windows Programming
    Replies: 0
    Last Post: 01-21-2009, 07:40 AM
  2. Button handler
    By Nephiroth in forum Windows Programming
    Replies: 8
    Last Post: 03-12-2006, 06:23 AM
  3. Setting focus
    By tyouk in forum Windows Programming
    Replies: 10
    Last Post: 11-04-2003, 11:12 PM
  4. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM
  5. setting focus on a dialog box control
    By face_master in forum Windows Programming
    Replies: 2
    Last Post: 05-14-2002, 04:11 PM