Good morning everyone. How to correctly remove the focus from TextBox? The Focused property for this control is read only. As an option, I set the focus on the label, but I don’t know how correct it is.

  • TextBox1.TabStop = False; ? - Sublihim
  • 2
    here it is necessary to understand that it is simply impossible to “remove” the focus. Focus somewhere should be. I do not know whether setting the focus on the label is the best place to focus, it's up to you. And TextBox1.TabStop = False; just makes control "non-focused" - Sublihim
  • one
    In general, for understanding, UX / UI details are needed here, sometimes after entering text in the field, it is more correct to shift the focus to the OK button, for example, and so on - Anatol
  • one
    Well, maybe it would be better to transfer the focus to the "search" button, if it exists, or to the search results - Anatol
  • one
    Returning to our conversation, before disturbing the community with a similar question, why not first of all find out for yourself what the focus is all about? I will not put a minus, but most of the questions are just like that. At this point I intend to end our discussion. - Alexander Muksimov

2 answers 2

Focused - a property that returns whether the element is currently in focus.

In order to focus on the element, you can use the winapi SetFocus function.

Code example:

 [DllImport("user32.dll")] private static void SetFocus(IntPtr Handle); void OnClick(object sender) { if((Button)sender.Name == "Button")) { SetFocus((Button)sender.Handle); } } 

Or you can install the hook on WndProc, but most likely you need it.

Learn more about WndProc on MSDN

  • one
    He asked to remove the focus - Sublihim
  • @Sublihim, what's stopping SetFocus (Window.Handle)? - user241285
  • one
    Hmm, downvote without explaining why a clear answer was given. - user241285
  • The answer, it seems, was different. - Alexander Puzanov

To remove the focus, you need to pass the parameter NULL to SetFocus :

hWnd [in, optional]

The keyboard input. If this parameter is NULL, keystrokes are ignored.

Code:

 [DllImport("user32.dll")] private extern static IntPtr SetFocus(IntPtr hWnd); // ... SetFocus(IntPtr.Zero); 
  • It works out. - Alexander Puzanov
  • one
    And what is better than moving the focus to another control? - Anatol
  • @Anatol SetFocus sends a WM_KILLFOCUS message to the original control and WM_SETFOCUS to a new one. If you specify NULL, the second message is not sent. Of course, this is unlikely to seriously improve performance. - kmv
  • one
    And if there are a lot of buttons, and everyone needs to remove the focus, how to be? - GooliveR