Click here to Skip to main content
Rate this: bad
good
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:
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 10-Dec-12 5:43am
Edited 10-Dec-12 7:05am
v2
Comments
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
good
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) {
  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.
  Permalink  
Comments
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
good
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.
 
—SA
  Permalink  

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



Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 10 Dec 2012
Copyright © CodeProject, 1999-2014
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