Fuzz Evans
Fuzz Evans

Reputation: 2943

How can I use a keypress to run a method?

My form has several buttons such as "Scan" and "Exit". I have seen in many programs where buttons will be useable by keypress. Lots of times the unique key to press is underlined in the text on the button (I don't know how to use an underline option on these forums!). I went to the form and added a keypress event:

private void Form1_KeyPress(object sender, KeyPressEventArgs key)
    {
        switch (key.ToString())
        {
            case "s":
                Run_Scan();
                break;
            case "e":
                Application.Exit();
                break;
            default:                    
                MessageBox.Show("I'll only accept 's' or 'e'.");
                break;
        }
    }

But then pressing 's' or 'e' on the form doesn't do anything. Not sure where I'm going wrong here?

Upvotes: 1

Views: 2809

Answers (4)

Kacey
Kacey

Reputation: 99

You can put an ampersand in front of the letter you want to make a hot key for the button in the Text property of your button. You can set the Text property from the Properties pane in the form designer, or you can set it programmatically. Below is an example of programmatic approach.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // make the 'B' key the hot key to trigger the key press event of button1
        button1.Text = "&Button";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("B");
    }
}

Upvotes: 1

Matt Brunell
Matt Brunell

Reputation: 10389

I think you are looking for what are called Access Keys: There are defined by the '&' symbol.

Get rid of your KeyPress event handler. You will not need it.

Change the text of your buttons to "&Scan" and "&Exit".

Also: Here are some guidelines about using access keys in windows applications.

Upvotes: 2

BDFun
BDFun

Reputation: 551

key.ToString() is the wrong method to call. You want to access the key property: key.KeyChar.

See the MSDN here for more info on the KeyPressEventArgs, which includes examples.

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

Overriding ProcessKeyCommand will accept input from anywhere on the form. You should add a modifier however, since pressing 's' or 'e' in a textbox, for example, will also trigger the action.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {

    switch (keyData)
    {
        case Keys.S:
            Run_Scan();                
            break;
        case Keys.E:
            Application.Exit();
            break;
        default:                    
            MessageBox.Show("I'll only accept 's' or 'e'.");                
            break;

    }        

    return base.ProcessCmdKey(ref msg, keyData);
}

Upvotes: 3

Related Questions