Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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:
C#
if(!searchTextBox.Focused)
{
    searchTextBox.Focus();
}

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
Updated 10-Dec-12 7:05am
v2
Comments
Philippe Mori 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.

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.
C#
private void MainForm_Activated(object sender, EventArgs e) {
  textBox1.Focus();
}

private void textBox1_Leave(object sender, EventArgs e) {
  textBox1.Focus();
}

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.

Alan.
 
Share this answer
 
Comments
Philippe Mori 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.
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.

—SA
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900