Is there a direct way to de-focus a TextBox
when clicking absolutely anywhere else in the form, whether or not the clicked thing itself can receive focus (e.g. toolbar buttons, toolbar and/or client area empty space, etc)? That is to say, the de-focusing click event could occur on a variety of other controls that know nothing about the focused control.
This question is rather similar to this one and this one, but the answers there are incomplete in that they don't offer any advice on when to perform the action (i.e. what event on what control).
I have a form (a UserControl
subclass) with draggable widgets on a panel along with a couple of toolbars. The draggable widgets are made up of PictureBox
es and Label
s. Double-clicking on a widget's label replaces the label with a TextBox
to allow the user to rename the component. The intent is to force focus to leave the TextBox
when clicking anywhere else, to cause validation to occur (as if the user had pressed Enter).
Here's a quick rundown of the heirarchy:
UserControl +- ToolStripContainer +- ToolStripConainer.TopToolStripPanel | +- ToolStrip +- ToolStripContainer.RightToolStripPanel | +- ToolStrip +- ToolStripContainer.ContentPanel +- CompositorPanel (subclass of Panel to provide proper transparency) +- UserControl (draggable widget) +- PictureBox +- Label +- TextBox
I can add event handlers to various other components on the form to force the focused TextBox to un-focus (i.e. programmatically move the focus to another element), but that seems kludgy and requires unrelated elements to be aware of the currently-focused TextBox.
I tried overriding OnMouseDown
on the outermost class (the containing UserControl
for everything, based on an idea presented here) but the method was never called.