Keyboard shortcut for a button

Tim S picture Tim S · Oct 21, 2011 · Viewed 54.3k times · Source

In C# (Microsoft Visual Studio 2010), how can I assign a keyboard shortcut to a button such as the following?

    private void closeButton_Click(object sender, EventArgs e)
    {
        // Close the program
        this.Close();
    }

I know I can use the "&" character in the button's Text and create an Alt - n shortcut, but I'd like to create a single keypress shortcut, such as c to execute the above.

Answer

dknaack picture dknaack · Oct 21, 2011

KeyDown is your friend ;) For example, if you want the shortcut key A while Shift is pressed, try this:

    void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.A && e.Shift) 
            // Do something
    }

If you want a "real" keyboard shortcut you can use hooks. Look at Stack Overflow question RegisterHotKeys and global keyboard hooks?.