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?
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.
public void ControlSetFocus( Control^ control )
{
// Set focus to the control, if it can receive focus.
if ( control->CanFocus )
{
control->Focus();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With