Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the focus from a TextBox in WinForms?

I need to remove the focus from several TextBoxes. I tried using:

textBox1.Focused = false; 

Its ReadOnly property value is true.

I then tried setting the focus on the form, so as to remove it from all the TextBoxes, but this also fails to work:

this.Focus(); 

and the function returns false when a textbox is selected.

So, how do I remove the focus from a TextBox?

like image 875
Callum Rogers Avatar asked Jul 16 '09 20:07

Callum Rogers


People also ask

What is TextBox focus () in C?

Textbox. Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus() . Follow this answer to receive notifications.

How do you Unfocus a button in C#?

In your form Load event you can set the focus on some other control. If you do not want the control to ever get focus via keyboard, you can also set its TabStop property to false. If you want that the button should not have focus when you open the form, then you need to correct the TabIndex property.

How do I delete all text boxes in a form?

public void ClearTextBoxes(Form form) { foreach (Control control in form. Controls) { if (control. GetType() == typeof(TextBox)) { control. Text = ""; } } } //Calling this Function var fm1 = new Form1(); ClearTextBoxes(fm1); //Smilarly From Form2 and So on var fm2 = new Form2(); ClearTextBoxes(fm2);


2 Answers

You need some other focusable control to move the focus to.

Note that you can set the Focus to a Label. You might want to consider where you want the [Tab] key to take it next.

Also note that you cannot set it to the Form. Container controls like Form and Panel will pass the Focus on to their first child control. Which could be the TextBox you wanted it to move away from.

like image 69
Henk Holterman Avatar answered Sep 17 '22 15:09

Henk Holterman


Focusing on the label didn't work for me, doing something like label1.Focus() right? the textbox still has focus when loading the form, however trying Velociraptors answer, worked for me, setting the Form's Active control to the label like this:

private void Form1_Load(object sender, EventArgs e)   {      this.ActiveControl = label1;        } 
like image 31
WhySoSerious Avatar answered Sep 20 '22 15:09

WhySoSerious