Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deselect textbox if user clicks elsewhere on the form?

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?

like image 234
John Smith Avatar asked Aug 26 '11 17:08

John Smith


2 Answers

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.

ScreenShot

like image 54
jp2code Avatar answered Sep 20 '22 23:09

jp2code


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);
like image 22
C.J. Manca Avatar answered Sep 22 '22 23:09

C.J. Manca