tags:

views:

67

answers:

2

I have to write a method on C# that associates a certain key (from the keyboard) to a specific button. For example, if I press A, the button that I created on a form application should appear like it is being pressed.

A: 

You would have to subscribe to click event of each button then take the appropriate action. So you wouldn't need one function but several.

Brownman98
I think you need to read the question again.
Charles
I think the OP is asking how to click a button using a specific key on the keyboard, not how to handle a button click...
Zach Johnson
+2  A: 
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.KeyPreview = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.MessageBox.Show("Ctrl-F was Pressed.");
    }
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.F))
        {
            button1.PerformClick();
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Note: To simulate click animation, make the Click event look like this:

    private void button1_Click(object sender, EventArgs e)
    {
        button1.FlatStyle = FlatStyle.Flat;
        System.Windows.Forms.MessageBox.Show("foo");
        button1.FlatStyle = FlatStyle.Standard;
    }

It's not perfect, but it works.

Robert Harvey
See my edit for the animation.
Robert Harvey