Respond to multiple KeyDown events

前端 未结 2 1830
粉色の甜心
粉色の甜心 2021-01-21 01:53

I\'m making a simple WinForm car race game. I\'ve got two objects - cars, and they move on the form when key is pressed (Form1KeyDown_Event).

The only thing is, that wh

2条回答
  •  别那么骄傲
    2021-01-21 01:57

    Here's a simple example of what you can do in order to listen to several keys at the same time, using the keyup and keydown events instead.

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    
    namespace WinFormTest {
        public partial class Form1 : Form {
            private readonly IDictionary downState;
    
            public Form1() {
                InitializeComponent();
                downState = new Dictionary();
                downState.Add(Keys.W, false);
                downState.Add(Keys.D, false);
    
                KeyDown += remember;
                KeyUp += forget;
            }
    
            protected override void OnLoad(EventArgs e) {
                base.OnLoad(e);
                Timer timer = new Timer() { Interval = 100 };
                timer.Tick += updateGUI;
                timer.Start();
            }
    
            private void remember(object sender, KeyEventArgs e) {
                downState[e.KeyCode] = true;
            }
    
            private void forget(object sender, KeyEventArgs e) {
                downState[e.KeyCode] = false;
            }
    
            private void updateGUI(object sender, EventArgs e) {
                label1.Text = downState[Keys.W] ? "Forward" : "-";
                label2.Text = downState[Keys.D] ? "Right" : "-";
            }
        }
    }
    

提交回复
热议问题