4

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

Aamir
  • 14,882
  • 6
  • 45
  • 69
  • 1
    This question was answered here : [http://stackoverflow.com/questions/1140250/how-to-remove-focus-from-a-textbox-in-c-winforms][1] [1]: http://stackoverflow.com/questions/1140250/how-to-remove-focus-from-a-textbox-in-c-winforms – mmorel Aug 30 '11 at 06:06
  • follow @mmorel1's links, you need to have another control thats visible=true but is out of the forms bounds. eg Textbox1.Left=-20; – Jeremy Thompson Aug 30 '11 at 06:15
  • @Jeremy Thompson: In that case, the focus will shift to that Textbox and my main form will stop receiving keys. for example, on Escape button on mainform, I hide the form. That wouldn't be possible. Any idea how to do that? – Aamir Aug 30 '11 at 06:26

3 Answers3

0

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.

0

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.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • By default, the KeyPreview is False which means that Keys are not previewed by the parent i.e., mainform. I tried setting it to True but that doesn't work either. – Aamir Aug 30 '11 at 06:06
0

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.

Mark Hall
  • 53,938
  • 9
  • 94
  • 111