How to remove the focus from a TextBox in WinForms?
Asked Answered
C

21

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?

Callihan answered 16/7, 2009 at 20:56 Comment(0)
L
86

You can add the following code:

this.ActiveControl = null;  //this = form
Limelight answered 25/6, 2014 at 19:59 Comment(5)
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.Rosinarosinante
This may be half the reason Microsoft added this property in the first place.Smoothshaven
This seems like the most elegant solution, it worked perfect in my case.Expenditure
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.Federica
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.Guerra
S
78

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;       
}
Sym answered 7/12, 2011 at 6:21 Comment(2)
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...Dusk
This works also for container controls like panels. I just wanted to remove focus completely and it worked: this.ActiveControl = panelOnMyForm;Adjustment
G
36

Try disabling and enabling the textbox.

Galantine answered 16/7, 2009 at 20:59 Comment(4)
This works pretty slick as it automatically selects the next control in the tab list in the meantime.Gastrointestinal
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!Raquelraquela
How can I disable it?Rubyeruch
@Rubyeruch textBox1.Enabled = false; will disable your textbox. and setting it to true will re-enable it.Jeanninejeans
C
36

You can also set the forms activecontrol property to null like

ActiveControl = null;
Chivaree answered 2/1, 2014 at 3:31 Comment(2)
I hope people scroll down all the way to this and don't just use the workaround marked as answerMousetrap
Still the best answer to this day, here buddy, take my upvote.Tine
F
10

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.

Ferous answered 16/7, 2009 at 21:16 Comment(1)
Tried everything else here and Select() worked for me.Digression
L
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.

Lapstrake answered 31/5, 2012 at 4:52 Comment(0)
A
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);
    }
}
Attractive answered 10/9, 2013 at 10:31 Comment(1)
Exactly the kind of solution I was looking for. Thanks!Forrest
P
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.

Purplish answered 29/3, 2014 at 5:46 Comment(0)
E
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;
}
Emit answered 15/2, 2011 at 15:11 Comment(0)
E
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.

Elodia answered 30/1, 2014 at 12:54 Comment(0)
M
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 :/

Ministry answered 10/3, 2012 at 17:50 Comment(0)
C
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();
                });
            }
        }
    }
Clamshell answered 6/4, 2014 at 21:36 Comment(0)
C
1

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^

Clairclairaudience answered 9/2, 2022 at 23:5 Comment(0)
N
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!

Niche answered 7/5, 2014 at 10:48 Comment(0)
K
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
Konikow answered 31/1, 2015 at 6:36 Comment(0)
A
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.

Arizona answered 6/8, 2015 at 10:16 Comment(0)
M
0

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

For eg:

txtEmpID.TabStop = false;
Muldon answered 31/1, 2017 at 14:2 Comment(0)
L
0

You can try:

textBox1.Enable = false;
Leu answered 10/9, 2020 at 10:39 Comment(0)
T
0

using System.Windows.Input

Keyboard.ClearFocus();
Tessi answered 19/2, 2021 at 14:25 Comment(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.Ora
P
0

I tried all of the solutions here, but none worked. However, Select() worked for me.

this.Select();//"this" still being the form.
Precursor answered 21/3, 2024 at 13:25 Comment(0)
J
-1

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

SetStyle(ControlStyles.Selectable, false);

After the InitializeComponent(); Source: https://mcmap.net/q/169092/-how-to-prevent-stealing-focus-when-clicking-on-a-usercontrol-duplicate

Example:

public partial class Main : UserControl
{

    public Main()
    {
        InitializeComponent();
        SetStyle(ControlStyles.Selectable, false);
    }
Joktan answered 25/1, 2018 at 15:53 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.