Tim S
Tim S

Reputation: 209

Keyboard shortcut for a button

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.

Upvotes: 18

Views: 57557

Answers (3)

Rahul Patel
Rahul Patel

Reputation: 351

if you want add Ctrl + S in switch statment so you can also try below code.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Control | Keys.S:
                // do something...
                return true;
            case Keys.Control |Keys.Alt | Keys.S:
                // do something...
                return true;
            case Keys.F2:
                // do something...
                return true;
            case Keys.F3:
                // do something...
                return true;
            case Keys.F4:
                // do something...
                return true;
            default:
                return base.ProcessCmdKey(ref msg, keyData);
        }
    }

Upvotes: 5

dknaack
dknaack

Reputation: 60556

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?.

Upvotes: 14

DN2048
DN2048

Reputation: 3804

Here's a different approach:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch(keyData)
    {
         case Keys.F2:
             // do something...
             return true;
         case Keys.F3:
             // do something...
             return true;
         case Keys.F4:
             // do something...
             return true;
         default:
             return base.ProcessCmdKey(ref msg, keyData);
    }            
}

You don't need to change KeyPreview value.

Upvotes: 8

Related Questions