我必须在C#上编写一个方法,将某个键(来自键盘)与特定按钮相关联。例如,如果我按 A ,我在表单应用程序上创建的按钮应该显示为正在按下它。
答案 0 :(得分:7)
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);
}
}
注意:要模拟点击动画,请使Click事件如下所示:
private void button1_Click(object sender, EventArgs e)
{
button1.FlatStyle = FlatStyle.Flat;
System.Windows.Forms.MessageBox.Show("foo");
button1.FlatStyle = FlatStyle.Standard;
}
它并不完美,但它确实有效。