I have a Form which covers the entire screen. I have a textbox
on it which is normally hidden but appears when a user clicks, drags mouse and then leaves. After that user can enter any value in the text box. Once entered, ideally user should be able to click outside of textbox and then the normal service should resume.
By normal service I mean that form should start getting all the events. What I have done so far is that on TextBox's KeyDown event; when Escape key is pressed, I have set the focus to the main form like this:
this.Focus(); //where this is mainform.
But this doesn't seem to work since Textbox
still keeps receiving all the keys. I have a KeyDown
event handler both for Form
and Textbox
and I have checked that all the KeyDown
events pass on to the TextBox. I have a TextBox
Leave event Handler as well which never gets called.
This TextBox
is th开发者_开发问答e only control on the form and the main form is used for drawing shapes (if that matters).
So, how can I make this TextBox
lose focus when user clicks outside of it.
if it works like in VB, for what I remember, try to set the form property KeyPreview
to false so all keys will be passed only to the focused control on the form.
If you set your form KeyPreview property to true, your form has first chance to handle any keystrokes that you make. If it is something you want to handle i.e. escape as in your comment above, handle it in your form's KeyDownEvent and mark it as handled so your textbox will not see it.
From above Msdn Page:
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus.
I guess back in '11 this didn't work, but now
this.ActiveControl = null;
works fine. However if you intend to use Tab to cycle controls, focusing a label with suitable TabIndex is the way.
精彩评论