What's the difference between Control.Select() and Control.Focus()?

你。 提交于 2019-11-26 18:33:51

问题


In WinForms, to set focus to a specific control, I always seem to wind up calling Control.Select() and Control.Focus() to get it to work.

What is the difference, and is this the correct approach?


回答1:


Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx




回答2:


Focus() is the low level function that actually sets the focus.

Select() is a higer-level method. It first looks iteratively upward in the control's parent hierarchy until it finds a container control. Then it sets that container's ActiveControl property (to the called control). The logic in those methods is not straightforward however, and there is special handling for UserControl containers.




回答3:


For an example of how they are different, if you are trying to set a control for a Forms App to default focus to when you open it, only Select() will work when called in the constructor after InitializeComponent(). Focus() will not.




回答4:


Just to add to this thread I found that when writing a user control that moved other controls from one form to another (newly created form). The original form could no longer select the control but using focus allowed it to do so. I think this emphasises the answers about the levels these methods work at. But it also means it is not simple enough to say use Select at the higher level since select no longer worked as expected on the orginal form (not that it should being I placed it into a different form - I accept that)




回答5:


Focus(), in some situations, can cause a window owning the control to gain focus if it didn't have focus. Select() does not cause a focus grab by the window.




回答6:


From personal experience I wrote a user control inheriting the Windows ComboBox. I had to write code to override the OnEnter event and I had a statement in there saying

If Me.Focused Then ... Else ...

However, unfortunately it returned the unexpected result. If I called MyCustomerComboControl.Select (in either Load, Shown or Activated events) it called the OnEnter method but failed to register it had the focus (i.e. Focused was False) but if I called Focus it worked. Furthermore Select worked if the form was open i.e. if I selected another control then re-selected the original control all was fine. So in any other circumstances other than my scenario, use Select because it says so above.



来源:https://stackoverflow.com/questions/802722/whats-the-difference-between-control-select-and-control-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!