A few keystrokes do different events in C #

private void Form1_KeyDown (object sender, KeyEventArgs e) {if (e.KeyCode == Keys.W) player1.moveUp (); if (e.KeyCode == Keys.NumPad8) player2.moveUp (); }

In the above code, the moveUp methods basically just increment the value. I want both keys to be pressed (or held) simultaneously, and both events will fire. Thanks, Nevik

+3
source share
2 answers

Get the status of the keyboard and check the status of the keys you want.

Events are not the best way to play games. You need a faster answer.

[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);
...
byte[] bCharData = new byte[256];
GetKeyboardState(bCharData);


, ,

[DllImport("user32.dll")]
static extern short GetKeyState(VirtualKeyStates nVirtKey);
...
public static bool IsKeyPressed(VirtualKeyStates testKey)
{
    bool keyPressed = false;
    short result= GetKeyState(testKey);

    switch (result)
    {
        case 0:
            // Not pressed and not toggled on.
            keyPressed = false;
            break;

        case 1:
            // Not pressed, but toggled on
            keyPressed = false;
            break;

        default:
            // Pressed (and may be toggled on)
            keyPressed = true;
            break;
    }

    return keyPressed;
}


.

, . , . :)

+4

, " ", , . KeyDown " ". , .

KeyUp "". Iff " ".

, . , .

+2
source

Source: https://habr.com/ru/post/1742159/


All Articles