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?
-
you dont want focus on textbox RT? – anishMarokey Apr 10 '11 at 18:45
-
Yep, I don't want to focus it... *if* I click somewhere else. It seems it holds focus even though I click somewhere else in the form. – Saturn Apr 10 '11 at 18:46
-
What do you want to have focus instead? – Lasse V. Karlsen Apr 10 '11 at 18:52
-
If the user didn't click on another textbox, I want to have focus on... nothing. Is that possible? – Saturn Apr 10 '11 at 18:53
4 Answers
Set the ActiveControl property of the form to null
to 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.

- 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
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.

- 922,412
- 146
- 1,693
- 2,536
-
-
1Bizarre question. The absence of the Click event, I guess. What is this all about? – Hans Passant Apr 10 '11 at 19:11
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

- 11
- 1
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.

- 81
- 3