Search code examples
c#winformstextboxfocussetfocus

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?


Solution

  • 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