pradeepradyumna
pradeepradyumna

Reputation: 1072

C# Ctrl+F doesn't work sometimes

I have a winforms application where in I have a textbox inside a form. I need to set focus to the textbox whenever I press 'Ctrl+F'. I have the following code in keyup event.

        private void frm_KeyUp(object sender, KeyEventArgs e)
        {     
            // Handle 'Ctrl + F' to Find    
            if (e.KeyData == (Keys.Control | Keys.F))
                SetFocus();
        } 

Problem I have here is that sometimes, even though the focus is on form and I try 'Ctrl+F' the condition doesn't run. I know, as soon as I press 'Ctrl' the event gets fired even before I would have pressed key 'F'. Eventually it works, when I press both the keys at the very same time. So to the user it might look like the screen is unresponsive to the keys sometimes.

How can I overcome this situation?

Upvotes: 1

Views: 648

Answers (1)

CodeCaster
CodeCaster

Reputation: 151644

You're using the KeyUp event and checking if the event contains both keys. This will only happen when you release both keys at the same time.

Change it to the KeyDown event instead, and check whether Ctrl was pressed at the moment F was pressed:

if (e.Control && e.KeyCode == Keys.F)
{
    // ...
}

Upvotes: 3

Related Questions