将按钮分配给特定键

时间:2014-03-22 07:54:48

标签: c# winforms

美好的一天!我希望按钮的行为类似于回车键,而另一个按钮的行为类似于退格键。有没有人知道如何做到这一点呢?

2 个答案:

答案 0 :(得分:0)

将表单上的KeyPreview属性设置为true。并将AcceptButton设置为按钮。

public Form1()
{
     InitializeComponent();

     // When this property is set to true, the form will receive all 
     // KeyPress, KeyDown, and KeyUp events. 
     this.KeyPreview = true;

     //This property enables you to designate a default action to occur when the 
     //user presses the ENTER key in your application. 
     this.AcceptButton = button1;

     this.KeyDown += Form1_KeyDown;
}

只需处理表单KeyDown事件,然后检查按键以获取除ENTER之外的其他键。

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Back)
     {
         BackSpaceButton_Click(null, null);  // Or do whatever you want
     }
}

答案 1 :(得分:0)

对于Enter按钮:如果将Form的AcceptButton属性设置为表单上的某个按钮,则默认情况下会获得该行为。

否则

在表单上将KeyPreview属性设置为True并处理其KeyDown事件。你可以这样做

public Form1()
{
    InitializeComponent();
    this.KeyPreview = true;
    this.KeyDown += Form1_KeyDown;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
            ProcessTabKey(true);//this will move textbox focus on Enter Key pressed.
    } 
    else if (e.KeyCode == Keys.Back)
    {
        BackSpaceButton_Click(null,null);//this is a button event,it fire when you press Back key
    }
}