How to deselect a text box if the user clicks elsewhere on the form?

Currently, it is not possible in my application to deselect a text box. The only way is to select another text box. My users and I agree that clicking anywhere on the form should unselect the current text field. I tried to override MouseDown on many controls and adjust focus to a random label, but it does not work for some controls, such as MenuStrip or scrollbars. Any ideas?

+6
source share
4 answers

Assuming there are no other controls in your forum, try adding a Panel control that can receive focus.

Set the TabIndex in the Panel control to less than your TextBox or NumericUpDown .

Now that your main form receives focus, the Panel should receive focus instead of the TextBox .

Screen shot

+2
source

I recently had a similar problem. My interface is very complex with lots of panels and tabs, so none of the simpler answers that I found worked.

My solution was to programmatically add a mouse click handler for each non-focusable control in my form that would try to focus any labels on the form. Focusing a specific tag will not work if it is on a different tab, so I ended the loop and concentrated all the tags.

Code to execute:

  private void HookControl(Control controlToHook) { // Add any extra "unfocusable" control types as needed if (controlToHook.GetType() == typeof(Panel) || controlToHook.GetType() == typeof(GroupBox) || controlToHook.GetType() == typeof(Label) || controlToHook.GetType() == typeof(TableLayoutPanel) || controlToHook.GetType() == typeof(FlowLayoutPanel) || controlToHook.GetType() == typeof(TabControl) || controlToHook.GetType() == typeof(TabPage) || controlToHook.GetType() == typeof(PictureBox)) { controlToHook.MouseClick += AllControlsMouseClick; } foreach (Control ctl in controlToHook.Controls) { HookControl(ctl); } } void AllControlsMouseClick(object sender, MouseEventArgs e) { FocusLabels(this); } private void FocusLabels(Control control) { if (control.GetType() == typeof(Label)) { control.Focus(); } foreach (Control ctl in control.Controls) { FocusLabels(ctl); } } 

Then add this to the Form_Load event:

 HookControl(this); 
+2
source

Since you probably have a shortcut or some other control on your winform, I would suggest a solution here and just focus on the shortcut when the Form is clicked.

In the worst case, you can even add a shortcut located at -100, -100, set it as the first in tab order and Focus () on the form click.

+1
source

I have a kind of β€œworkaround” for you. Simple but different control (which can get focus) in the background. I checked this for a GridView (which will paint your gray), but you have to do this with a custom control in the right color or just set the backgroundcolor gridview (doh). Thus, every time the user clicks on the background, the background control focuses.

0
source

Source: https://habr.com/ru/post/895988/


All Articles