133

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?

Shin
  • 664
  • 2
  • 13
  • 30
Callum Rogers
  • 15,630
  • 17
  • 67
  • 90

20 Answers20

84

You can add the following code:

this.ActiveControl = null;  //this = form
Tzah Mama
  • 1,547
  • 1
  • 13
  • 25
FTheGodfather
  • 902
  • 7
  • 6
  • 8
    I believe this is the best answer. A lot of the other methods like "Focus" if you read MSDN, are listed as low level methods for control designers. If you want everything else to be "not selected" this appears to be the easiest approach since, well, it's just one small line. – Rostov Jul 16 '14 at 15:42
  • 2
    This may be half the reason Microsoft added this property in the first place. – Panzercrisis Oct 20 '16 at 19:19
  • This seems like the most elegant solution, it worked perfect in my case. – NetWave Feb 03 '20 at 15:21
  • I really want this answer to work because it just seems like it should, but in my case it didn't work because whilst it did trigger the Leave event it did not trigger the Validating/Validated events. – Rhys Jones May 26 '20 at 16:39
  • 1
    This is certainly the simplest and most effective solution. You could add this line to the Form's Activated event and prevent the child textbox from automatically selecting all of the text. – Special Sauce Mar 09 '21 at 03:09
77

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;       
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
WhySoSerious
  • 1,930
  • 18
  • 18
  • 11
    i wish i could give you million arrow up's. i tried EVERYTHING else that people suggested, this is the only one that worked. for some reason, the textbox ALWAYS stole the focus from everything... – eladyanai Mar 12 '13 at 14:58
  • 3
    This works also for container controls like panels. I just wanted to remove focus completely and it worked: `this.ActiveControl = panelOnMyForm;` – Tim Schmelter Apr 09 '13 at 14:32
36

Try disabling and enabling the textbox.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
  • 6
    This works pretty slick as it automatically selects the next control in the tab list in the meantime. – Nick May 12 '10 at 23:50
  • 3
    I am developing in Silverlight using MVVM and implemented this using a behavior targeting a TextBox. Since I didn't have another UIElement handy to set focus to the Disable/Enable solution worked wonders. Thanks! – Albert Oldfield Jun 10 '10 at 22:31
  • How can I disable it? – miguelmpn Dec 22 '15 at 11:11
  • 2
    @miguelmpn `textBox1.Enabled = false;` will disable your textbox. and setting it to `true` will re-enable it. – Raktim Biswas Aug 16 '16 at 17:10
35

You can also set the forms activecontrol property to null like

ActiveControl = null;
Amnesh Goel
  • 2,617
  • 3
  • 28
  • 47
marcigo36
  • 495
  • 4
  • 7
9

Focus sets the input focus, so setting it to the form won't work because forms don't accept input. Try setting the form's ActiveControl property to a different control. You could also use Select to select a specific control or SelectNextControl to select the next control in the tab order.

Velociraptors
  • 2,012
  • 16
  • 22
8

Try this one:

First set up tab order.

Then in form load event we can send a tab key press programmatically to application. So that application will give focus to 1st contol in the tab order.

in form load even write this line.

SendKeys.Send("{TAB}");

This did work for me.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
charith rasanga
  • 124
  • 2
  • 3
4

A simple solution would be to kill the focus, just create your own class:

public class ViewOnlyTextBox : System.Windows.Forms.TextBox {
    // constants for the message sending
    const int WM_SETFOCUS = 0x0007;
    const int WM_KILLFOCUS = 0x0008;

    protected override void WndProc(ref Message m) {
        if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;

        base.WndProc (ref m);
    }
}
VladL
  • 12,769
  • 10
  • 63
  • 83
4

This post lead me to do this:

ActiveControl = null;

This allows me to capture all the keyboard input at the top level without other controls going nuts.

Kristopher Ives
  • 5,838
  • 7
  • 42
  • 67
3

I made this on my custom control, i done this onFocus()

this.Parent.Focus();

So if texbox focused - it instantly focus textbox parent (form, or panel...) This is good option if you want to make this on custom control.

Tommix
  • 443
  • 4
  • 15
3

I've found a good alternative! It works best for me, without setting the focus on something else.

Try that:

private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{    
    e.SuppressKeyPress = true;
}
FrostyFire
  • 3,212
  • 3
  • 29
  • 53
kaspi
  • 31
  • 1
2

It seems that I don't have to set the focus to any other elements. On a Windows Phone 7 application, I've been using the Focus method to unset the Focus of a Textbox.

Giving the following command will set the focus to nothing:

void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        Focus();
    }
}

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

It worked for me, but I don't know why didn't it work for you :/

Bhawk1990
  • 126
  • 1
  • 5
1
    //using System;
    //using System.Collections.Generic;
    //using System.Linq;

    private void Form1_Load(object sender, EventArgs e)
    {
        FocusOnOtherControl(Controls.Cast<Control>(), button1);
    }

    private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
    {
        foreach (var control in controls)
        {
            if (control.GetType().Equals(typeof(TextBox)))
            {
                control.TabStop = false;
                control.LostFocus += new EventHandler((object sender, EventArgs e) =>
                {                     
                    focusOnMe.Focus();
                });
            }
        }
    }
Torus
  • 11
  • 1
0

The way I get around it is to place all my winform controls. I make all labels and non-selecting winform controls as tab order 0, then my first control as tab order 2 and then increment each selectable control's order by 1, so 3, 4, 5 etc...

This way, when my Winforms start up, the first TextBox doesn't have focus!

0

you can do this by two method

  • just make the "TabStop" properties of desired textbox to false now it will not focus even if you have one text field
  • drag two text box

    1. make one visible on which you don't want foucus which is textbox1
    2. make the 2nd one invisible and go to properties of that text field and select

tabindex value to 0 of textbox2

  1. and select the tabindex of your textbox1 to 1 now it will not focus on textbox1
Adiii
  • 54,482
  • 7
  • 145
  • 148
0

If all you want is the optical effect that the textbox has no blue selection all over its contents, just select no text:

textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();

After this, when adding content with .Text += "...", no blue selection will be shown.

Roland
  • 4,619
  • 7
  • 49
  • 81
0

Please try set TabStop to False for your view control which is not be focused.

For eg:

txtEmpID.TabStop = false;
0

You can try:

textBox1.Enable = false;
Vương Hữu Thiện
  • 1,460
  • 14
  • 21
0

using System.Windows.Input

Keyboard.ClearFocus();
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Feb 19 '21 at 14:36
0

Kinda late to the party in 2022, however none of the solutions here worked for me (idk why) using .Net_6.0_windows, so I've come up with this solution:

Label focusoutLabel = new Label() { 
    Text = "",
    Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
    Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;

^Place this code to your Form load handler^

TDiblik
  • 522
  • 4
  • 18
-1

In the constructor of the Form or UserControl holding the TextBox write

SetStyle(ControlStyles.Selectable, false);

After the InitializeComponent(); Source: https://stackoverflow.com/a/4811938/5750078

Example:

public partial class Main : UserControl
{

    public Main()
    {
        InitializeComponent();
        SetStyle(ControlStyles.Selectable, false);
    }
Alvaro Rodriguez Scelza
  • 3,643
  • 2
  • 32
  • 47