Currently in my application it is impossible to deselect a textbox. The only way is to select another textbox. My users and I agree that clicking anywhere else on the form should deselect the current textbox. I tried overriding the MouseDown on many controls and having the focus set to a random label but it doesn't work for some controls like the MenuStrip or scrollbars. Any ideas?
Assuming you have no other controls on your forum, try adding a Panel control that can receive focus.
Set the TabIndex
on the Panel
control to something less than your TextBox
or NumericUpDown
control has.
Now, when your main form receives focus, the Panel
should receive the focus instead of the TextBox
area.
I had a similar issue recently. My interface is very complex with lots of panels and tab pages, so none of the simpler answers I found had worked.
My solution was to programatically add a mouse click handler to every non-focusable control in my form, which would try to focus any labels on the form. Focusing a specific label wouldn't work when on a different tab page, so I ended up looping through and focusing all labels.
Code to accomplish is as follows:
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);
}
}
And then add this to your Form_Load event:
HookControl(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With