Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

winforms

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?

like image 673
Charlie Avatar asked Jun 16 '09 14:06

Charlie


2 Answers

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.

like image 142
Charlie Avatar answered Sep 20 '22 08:09

Charlie


   public void ControlSetFocus( Control^ control )
   {

      // Set focus to the control, if it can receive focus.
      if ( control->CanFocus )
      {
         control->Focus();
      }
   }    
like image 40
Robert Harvey Avatar answered Sep 20 '22 08:09

Robert Harvey