Charlie
Charlie

Reputation: 45052

How to specify which control should be focused when a form opens?

Whenever a Form is opened, the system automatically focuses one of the controls for you. As far as I can tell, the control that gets focus is the first enabled control in the tab order, as per Windows standard behavior.

The question is how to change this at run time without having to dynamically reshuffle the tab order. For instance, some forms might want to vary the initially-focused control based on program logic, to put focus in the most appropriate control. If you just focus some other control inside your OnLoad handler, the default logic executes anyway and re-focuses the default control.

If you're writing in C/C++ and using a raw window procedure or MFC, you can return 0 (FALSE) from your WM_INITDIALOG handler, and the default focusing logic gets skipped. However, I can't find any way to do this in Windows Forms. The best I've come up with is to use BeginInvoke to set the focus after the OnLoad finishes, like so:

protected override void OnLoad( System.EventArgs e )
{
    base.OnLoad( e );
    // ... code ...
    BeginInvoke( new MethodInvoker( () => this.someControl.Focus() ) );
}

There must be some proper way to do this - what is it?

Upvotes: 8

Views: 2886

Answers (3)

Adam Fox
Adam Fox

Reputation: 1326

Instead of using the OnLoad event can't you use Form.Activated or Form.Shown events to see if they are called post rendering of control focus?

Upvotes: 0

Charlie
Charlie

Reputation: 45052

After digging around through Reflector, I found what appears to be the "correct" way to do this: using ContainerControl.ActiveControl. This can be done from OnLoad (or elsewhere; see the docs for limitations) and directly tells the framework which control you want to be focused.

Example usage:

protected override void OnLoad( System.EventArgs e )
{
    base.OnLoad( e );
    // ... code ...
    this.ActiveControl = this.someControl;
}

This seems like the cleanest and simplest solution so far.

Upvotes: 13

Robert Harvey
Robert Harvey

Reputation: 180798

   public void ControlSetFocus( Control^ control )
   {

      // Set focus to the control, if it can receive focus.
      if ( control->CanFocus )
      {
         control->Focus();
      }
   }    

Upvotes: 1

Related Questions