Associating keys to buttons on a Windows Form

99封情书 提交于 2021-02-19 01:14:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2626530/associating-keys-to-buttons-on-a-windows-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!