[c#] 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?

This question is related to c# .net winforms textbox focus

The answer is


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.


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.


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.


using System.Windows.Input

Keyboard.ClearFocus();

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

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;       
}

You can add the following code:

this.ActiveControl = null;  //this = form

You can also set the forms activecontrol property to null like

ActiveControl = null;

You can try:

textBox1.Enable = false;

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);
    }

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

For eg:

txtEmpID.TabStop = false;

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!


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.


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);
    }
}

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.


Try disabling and enabling the textbox.


    //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();
                });
            }
        }
    }

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;
}

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 :/


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox

Examples related to focus

How to remove focus from input field in jQuery? Set element focus in angular way Bootstrap button - remove outline on Chrome OS X How can I set focus on an element in an HTML form using JavaScript? Set Focus on EditText Mobile Safari: Javascript focus() method on inputfield only works with click? Correct way to focus an element in Selenium WebDriver using Java Prevent the keyboard from displaying on activity start What are some reasons for jquery .focus() not working? How can I set the focus (and display the keyboard) on my EditText programmatically