且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WinForm:按下多个键

更新时间:2023-12-03 10:34:10

当您按住按键时,您依赖于键盘控制器重复按键.当您按下另一个键时,它停止工作.这需要不同的方法.

You are relying on the keyboard controller repeating the key when you hold it down. That stops working when you press another key. This requires a different approach.

首先,您需要一个枚举,用 NotMoving、MovingLeft 和 MovingRight 等值指示飞船的运动状态.将这种类型的变量添加到您的类中.您将需要 KeyDown KeyUp 事件.当您获得 KeyDown 时,例如 Keys.Left,然后将变量设置为 MovingLeft.当您获得 Keys.Left 的 KeyUp 事件时,首先检查状态变量是否仍为 MovingLeft,如果是,则将其更改为 NotMoving.

First you need an enum that indicates the motion state of the spaceship with values like NotMoving, MovingLeft and MovingRight. Add a variable of that type to your class. You'll need both the KeyDown and KeyUp events. When you get a KeyDown for, say, Keys.Left then set the variable to MovingLeft. When you get the KeyUp event for Keys.Left then first check if the state variable is still MovingLeft and, if it is, change it NotMoving.

在您的游戏循环中,使用变量值移动飞船.一些示例代码:

In your game loop, use the variable value to move the spaceship. Some sample code:

    private enum ShipMotionState { NotMoving, MovingLeft, MovingRight };
    private ShipMotionState shipMotion = ShipMotionState.NotMoving;

    protected override void OnKeyDown(KeyEventArgs e) {
        if (e.KeyData == Keys.Left)  shipMotion = ShipMotionState.MovingLeft;
        if (e.KeyData == Keys.Right) shipMotion = ShipMotionState.MovingRight;
        base.OnKeyDown(e);
    }
    protected override void OnKeyUp(KeyEventArgs e) {
        if ((e.KeyData == Keys.Left  && shipMotion == ShipMotionState.MovingLeft) ||
            (e.KeyData == Keys.Right && shipMotion == ShipMotionState.MovingRight) {
            shipMotion = ShipMotionState.NotMoving;
        }
        base.OnKeyUp(e);
    }

    private void GameLoop_Tick(object sender, EventArgs e) {
        if (shipMotion == ShipMotionState.MovingLeft)  spaceShip.MoveLeft();
        if (shipMotion == ShipMotionState.MovingRight) spaceShip.MoveRight();
        // etc..
    }