views:

1079

answers:

2

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?

I would also like some tips to how make this only happen when regular keys are pressed. So not like, arrow keys, modifier keys, function keys, etc. But this I will probably figure out a way to do. The previous issue on the other hand, I am not so sure how I should tackle...

+3  A: 

You will get the first key stroke as part of the KeyDown event. You can save it to the textbox yourself.

SDX2000
But how does this work with non-ascii letters and stuff? Especially thinking of various modifier keys etc being used...
Svish
+4  A: 

As an addition to the answer from SDX2000, have a look at the MSDN article for the KeyDown event. It also refers to the KeyPressed event, which is fired after the KeyDown event, I think it is better suited for what you want to do.

Quoting MSDN:

A KeyPressEventArgs specifies the character that is composed when the user presses a key. For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.

private void YourEventHandler(object Sender, KeyPressEventArgs Args)
{
    if(!searchTextBox.Focused)
    {
        searchTextBox.Focus();
        searchTextBox.Text += Args.KeyChar;
        // move caret to end of text because Focus() selects all the text
        searchTextBox.SelectionStart = searchTextBox.Text.Length
    }
}

I'm actually not certain that you can use += to append a char to a string, so you need to check on that. And I don't know what happens when the user hits return, better follow up an that issue as well.

Treb
+= seems to work. Although the property is called Text, not Value. So you could maybe fix that in your example :)
Svish
Also, I had to add searchTextBox.SelectionStart = searchTextBox.Text.Length on the end, cause when I Focus() it selects all the text. So when the user continues to type, it all goes away.. :p Other than that, this totally works :)
Svish
Right, will edit my answer accordingly.
Treb
the SelectionStart line needs to be the last one to work properly =)
Svish
Now that you mention it... fixed my answer (again)
Treb