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

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


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);