How to assign a shortcut key (something like Ctrl+F) to a text box in Windows Forms?

Shekhar picture Shekhar · Mar 23, 2010 · Viewed 31.7k times · Source

I am building a tool using C#. It's a Windows application. I have one text box on a form, and I want to assign focus to that text box when the user presses Ctrl + F or Ctrl + S.

How do I do this?

Answer

Aseem Gautam picture Aseem Gautam · Mar 23, 2010

One way is to override the ProcessCMDKey event.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.S))
    {
        MessageBox.Show("Do Something");
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

EDIT: Alternatively you can use the keydown event - see How to capture shortcut keys in Visual Studio .NET.