45

For a C# Windows Forms application, how do I set the default focus to a given control when my application starts?

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
Dribbel
  • 2,060
  • 2
  • 17
  • 29
  • Related post - [How to set focus to a control in a Windows Forms application?](https://stackoverflow.com/q/4059512/465053) – RBT May 09 '21 at 12:34

1 Answers1

83

The one with the minimum tab index automatically gets the focus (assuming the TabStop property is set to true). Just set the tab indices appropriately.

By the way, Visual Studio provides a way to easily set tab indices by just clicking on the controls in the order you want. You can activate this feature by choosing "Tab Order" option in the "View" menu when you are in the form design view.

You can also manually give the focus to a control by calling its Select method when the form loads.

oldmud0
  • 147
  • 2
  • 11
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 2
    Great answer. Note that the TabIndex of container controls (panels etc) take precedence over their children - even if the container's TabStop is false. View > Tab Order makes this clear. – Dunc Jul 23 '13 at 17:22
  • For some reason some control completely in the middle is selected when my form opens... not sure if it's related to the code for enabling/disabling items and filling in values on startup, but it doesn't seem like that text box has any right to be selected either way. Guess I'll have to do it manually. – Nyerguds Feb 11 '16 at 09:43
  • Maybe you added a GroupBox or a Panel later on in which you shoved the initial control that had a 0 tab index? Because then that control would still have a tab index of 0, but only relative to the controls in the GroupBox! Its actual tab-index from "outside the GroupBox" would be something like X,N where X is the tab-index of the GroupBox (say 10, because it was added later), and N is the tab-index of your control relative to the other controls inside the GroupBox. So now the tab-index for the control is 10,0. By the way "Tab Order" in View menu is really useful! Thanks @Mehrdad Afshari – Redoman Mar 18 '16 at 11:41
  • 1
    That "easy way" is a hard one. Not only one would need to click a dozens of times on a single widget just to reset it to zero — it doesn't even allow to! E.g. clicking to a textbox I need, switches back and forth between numbers `13.0.7.0` and `13.0.7.1`. Not even close to what I want. Is there other way to get it working? Case-insensitive grepping through the code came up with nothing relevant to the word `order`. – Hi-Angel Aug 25 '16 at 07:40