Click here to Skip to main content
11,640,445 members (62,294 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
I want to activate a search textbox when the user starts to type something (even if the textbox isnt focused right then). I have come as far as setting KeyPreview on the form to true. Then in the KeyDown event handler, I have this:
This almost works. The textbox is focused, but the first typed letter is lost. I guess this is because the textbox never really gets the event, since it wasn't focused when it happend. So, do anyone have a clever solution to how I could make this work like it should?
Posted 10-Dec-12 5:43am
Edited 10-Dec-12 7:05am
Philippe Mori at 10-Dec-12 18:57pm
This is a very, very bad idea as keys like TAB or ALT + underline letter or space bar when a button would have the focus would all be broken.

By doing that, you would mkake your application inconsistant with the rest of the system.

The only think you should do is to put the focus on the text box when the form is displayed or after some commands when it make sense.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

One solution to this problem would be to ensure that the textbox never loses focus by installing handlers for the Form Activate event and the TextBox Leave event.
private void MainForm_Activated(object sender, EventArgs e) {
private void textBox1_Leave(object sender, EventArgs e) {
The Activated handler will ensure than the textbox is always given focus when the form becomes active and the Leave handler will keep it that way.

Philippe Mori at 10-Dec-12 18:46pm
It would be a bad idea as it would make the form not works with keyboard only for example when the user press the TAB key.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

You cannot; and it makes no sense. "Starts to type", quite formally, means something which happens only if a control is already focused. Why does not make sense? Because for a currently focused control these keyboard events may also mean something.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Mika Wendelius 240
1 CPallini 209
2 OriginalGriff 165
3 Sergey Alexandrovich Kryukov 139
4 F-ES Sitecore 120
0 Mika Wendelius 200
1 OriginalGriff 145
2 CPallini 115
3 jgakenhe 40
4 sasanka sekhar panda 30

Advertise | Privacy | Mobile
Web02 | 2.8.150731.1 | Last Updated 10 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100