-2

仍然是一个编程菜鸟,但我正在变得更好。

现在我正在编写一个西蒙说游戏。有四个按钮。我的代码在功能方面工作完美。但是,我不想单击按钮,而是将击键绑定到它。我见过许多令人困惑的方法和一些相当简单的方法。但是,我还没有找到 Visual Studio 2008 的键绑定解决方案。所以基本上,当程序运行时,如果我按下“A”按钮,那么我希望我的程序表现得就像刚刚点击了红色按钮一样。谢谢!

4

3 回答 3

3

You want to listen to a keystroke event on your form. To do this, select your form in the visual studio designer and go to the properties panel. Click the lightning bolt (events) icon and double clikc on the KeyDown event.

Event Properties

This will generate the following code

private void Form1_KeyDown(object sender, KeyEventArgs e)
{

}

This will fire whenever a key is pressed down. Next, you want to check which key was clicked and handle appropriately

Inside of your the KeyDown method, add the following code:

if (e.KeyCode == Keys.A)
{
    //Do stuff when 'A' Key is pressed
}

Also, consider adding a switch statement if you're trying to listen to multiple keys and determine the action based on that, for example:

switch (e.KeyCode ) {
    case Keys.A:
        //Preform Code for A
        break;
    case Keys.W:
        //Preform Code for W
        break;
    //You can add as many case statments as you like...
}

You'll have to make sure that KeyPreview is set to true so that keyboard events properly register with the form. This can be done during initialization or on the form properties panel.

Set KeyPreview to True

To call the same code is pretty straight forward. You can either have the red button Click event call into the same method as the keystroke event. If you really wanted, you could leave the logic in the button click event and just call that method and pass nulls as arguments

For example, you could do the following:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        RedButton_Click(null, null);
    }
}

private void RedButton_Click(object sender, EventArgs e)
{
    //Do red button stuffs
}
于 2013-05-07T15:35:45.867 回答
2

使用KeyDown事件。

yourControl.KeyDown += new KeyEventHandler(control_KeyDown);

static void control_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        //The 'A' key has been pressed
    }
}
于 2013-05-07T15:27:54.733 回答
0

使用OnkeyPress您的事件Form

protected override void OnKeyPress(KeyPressEventArgs e)
{
        if (e.KeyChar == 'A')
              //your code
}

只需在您的代码中编写此form代码。

于 2013-05-07T15:28:17.373 回答