5

I have a textbox, and I want it so if the user clicks anywhere on the form that is not the textbox itself, such textbox will lose focus. Any ideas?

Saturn
  • 17,888
  • 49
  • 145
  • 271

4 Answers4

5

Set the ActiveControl property of the form to nullto achieve what you want.

Note that this is contrary to what all other programs does, so it'll be a disconnect between the user expectations and the actual user experience. I would advice against it.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • What's missing from your answer (and thus makes it less useful for me, with a similar question) is *when* to set that property (i.e. what event). My form has toolbars, blah blah blah, and I don't want to have to hook special code into every single button handler to clear the focus of the textbox in question. Clicking a toolbar button does not naturally un-focus the textbox. :-( – Brian A. Henning Nov 02 '16 at 13:25
4

Something needs to get the focus. That something is what you should click. That better be another control on the form, the form itself doesn't want the focus. It has no use for it. Or click, say, the Start button.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

Just put your controls in a panel and set your focus on an harmless control (Like a label) :

Private Sub Panel1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel1.Click
        Label1.Focus()
End Sub
Eric
  • 11
  • 1
0

I added this because my reputation does not have sufficient credits (only been coding 30+years lol). I found a use for Lasse's Activecontrol to Nothing (VB) answer - I used it during the form deacivate event so when that form lost focus it took focus away from the active control. This is what I and the user wants (I highlight focussed controls for them via my custom control library and since it does not have focus from the user point of view I needed to remove it from the control when the (parent) form is not in use). The use was unusual as I was creating some forms "on the fly" as a kind of control detach/unpin feature I am writing.

That said it is early in my testing so it may not make production yet but it is a longwinded way of saying that I couldn't upvote Lasse and that there are odd occasions where his answer is enlightening.

Tim
  • 81
  • 3