简体   繁体   中英

C# KeyDown Event in Game loop

I'm working on a game in C# and have gotten stuck. So the background is consistently moving, and this is done in a loop wit a Timer to insure that the background moves consistently. Now, I need to check if the user has pressed Spacebar to move the player up. How do I check if there is a keydown event? I can't use a KeyDown event sub because the game loop is consistently working, so the KeyDown event sub won't work. Just looking for some direction here. Thanks!

In your tick event you can check for

if (Keyboard.IsKeyDown(Key.Space))
{
    ... Do stuff
}

Just guessing as you didn't provided any code.

Try to call Application.DoEvents(); in every loop and use the KeyDown as you intend.

EDIT:

OK, this means you are NOT using the game loop, but you have event driven application (usual win application). Call to Application.DoEvents() lets the windows to process all callbacks in regular game loop (not your case).

I have updated code again to show how it works - I believe learning by examples is good, but first, you must learn the basics (sorry, but the game is too complicated for learning the C#)...

private bool isKeyUpPressed;
private void tmrTick_Tick(object sender, EventArgs e) { 
    if (isKeyUpPressed)
    {
        // move player up
    }
} 
private void Form1_KeyDown(object sender, KeyEventArgs b) { 
    isKeyUpPressed = b.KeyCode == Keys.Up;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM