[ACCEPTED]-What's the difference between Control.Select() and Control.Focus()?-behavior
Focus() is the low level function that actually 9 sets the focus.
Select() is a higer-level 8 method. It first looks iteratively upward 7 in the control's parent hierarchy until 6 it finds a container control. Then it sets 5 that container's ActiveControl property 4 (to the called control). The logic in those 3 methods is not straightforward however, and 2 there is special handling for UserControl 1 containers.
Focus is a low-level method intended primarily 4 for custom control authors. Instead, application 3 programmers should use the Select method 2 or the ActiveControl property for child 1 controls, or the Activate method for forms.
For an example of how they are different, if 5 you are trying to set a control for a Forms 4 App to default focus to when you open it, only 3 Select() will work when called in the constructor 2 after InitializeComponent(). Focus() will 1 not.
Just to add to this thread I found that 12 when writing a user control that moved other 11 controls from one form to another (newly 10 created form). The original form could 9 no longer select the control but using focus 8 allowed it to do so. I think this emphasises 7 the answers about the levels these methods 6 work at. But it also means it is not simple 5 enough to say use Select at the higher level 4 since select no longer worked as expected 3 on the orginal form (not that it should 2 being I placed it into a different form 1 - I accept that)
Focus(), in some situations, can cause a 3 window owning the control to gain focus 2 if it didn't have focus. Select() does not 1 cause a focus grab by the window.
From personal experience I wrote a user 13 control inheriting the Windows ComboBox. I 12 had to write code to override the
OnEnter event 11 and I had a statement in there saying
If Me.Focused Then ... Else ...
However, unfortunately 10 it returned the unexpected result. If I 9 called
MyCustomerComboControl.Select (in either Load, Shown or Activated 8 events) it called the
OnEnter method but failed 7 to register it had the focus (i.e. Focused 6 was False) but if I called Focus it worked. Furthermore 5
Select worked if the form was open i.e. if I selected 4 another control then re-selected the original 3 control all was fine. So in any other circumstances 2 other than my scenario, use
Select because it 1 says so above.
More Related questions