Search code examples
c#winformsc#-3.0keyboard-shortcutsctrl

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


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?


Solution

  • Capture the KeyDown event and place an if statement in it to check what keys were pressed.

    private void form_KeyDown(object sender, KeyEventArgs e)
    {
        if ((e.Control && e.KeyCode == Keys.F) || (e.Control && e.KeyCode == Keys.S)) {
            txtSearch.Focus();
        }
    }