C# Winforms textbox focus(2 methods)

Lionsure 2020-07-13 Original by the website

Sometimes, the textbox in Winform will automatically focus; sometimes, it will not; why is this happening? This is related to one of the ways it is focused. When the textbox is first pulled to the Form, it will automatically focus, otherwise it will not. The specific reasons will be described below.

There are two methods for Winforms textbox focus, one is using the Focus() method, and the other is through the control index. The specific implementation steps or codes of these two methods are introduced below.

 

I. C# Winforms textbox focus with Focus method

1. To use Textbox's Focus() method, you need to write code in the Form's Activated event. First add an Activated event to the Form1, expand the "Properties" window on the right, as shown in Figure 1:

C# Winforms textbox focus

Figure 1

Select the "Event" icon, enter Form1_Activated on the right of Activated, click anywhere to open the code file of Form.

 

2. Add the following code in the Form1_Activated event:

private void Form1_Activated(object sender, EventArgs e) {

       textBox1.Focus()

}

In this way, open the Form1, the focus will automatically appear in textbox.

 

II. C# Winforms textbox focus with tabindex

If the tabindex of textbox is set to 0, it will automatically focus, which is why we sometimes do not set the textbox focus, but the cursor will automatically appear. Generally speaking, the textbox is the first to be pulled into the Form, then its tabindex is 0. The method to set tabindex to 0 is as follows:

1. Select textbox, expand the "Properties" window on the right, and find TabIndex, as shown in Figure 2:

C# Winforms textbox focus with tabindex

Figure 2

2. Enter 0 to the right of TabIndex, run the program and the textbox focus will appear.

 

III. Attention

1. The textbox must be displayed(that is, Visible is True) and enabled (that is, Enabled is True), the focus(cursor) appears.

2. Use the textbox.Focus() method to set the focus. You cannot write code to the form load event(i.e. Form1_Load), otherwise it is invalid.