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.
2 answers
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
- oneHe asked to remove the focus - Sublihim
- @Sublihim, what's stopping SetFocus (Window.Handle)? - user241285
- oneHmm, 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
- oneAnd 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
- oneAnd if there are a lot of buttons, and everyone needs to remove the focus, how to be? - GooliveR
|
TextBox1.TabStop = False;? - SublihimTextBox1.TabStop = False;just makes control "non-focused" - Sublihim