detecting multiple keys press

I am writing a multiplayer mode for my little c# game. I want two users to be able to control their car simultaneous from the same keyboard. The problem is that when I try to keep more than 2 keys pressed (let's say accelerate and left for both players...totally 4 keys) the computer doesn't recognize them (and in my case it starts beeping from the internal speaker). How can I solve this problem
If you keep down only two keys everything it's ok... To make it work I used the keydown and keyup events of the form and an array of bool[] to store if a certain key is kept pressed.
If you have any idea how to solve it.. please reply. I have the feeling that is something more complex and that I will have to work directly with the keyboard input... 10X



Answer this question

detecting multiple keys press

  • Chinese Boy

    Maybe a better way to detect the keys currently pressed is to use api code.

    The following example show the use for this method, create a form, add 4 labels to it (label1,2,3,4) and on the load form event call the method :CheckKeysThread();

    Try to press up, down, right, left.

    Here is the code you need to add to the form:

    [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]

    public static extern UInt16 GetAsyncKeyState(int vKey);

    public static bool IsKeyPressed(Keys k)

    {

    int s = (int)GetAsyncKeyState((int)k);

    s = (s & 0x8000) >> 15;

    return (s == 1);

    }

    public void CheckKeysThread()

    {

    Thread t = new Thread(new ThreadStart(CheckKeys));

    t.Start();

    }

    public void CheckKeys()

    {

    while (true)

    {

    UpdateText(label1, "UP = " + IsKeyPressed(Keys.Up));

    UpdateText(label2, "down = " + IsKeyPressed(Keys.Down));

    UpdateText(label3, "left = " + IsKeyPressed(Keys.Left));

    UpdateText(label4, "Right = " + IsKeyPressed(Keys.Right));

    Thread.Sleep(1000);

    }

    }

    private delegate void UpdateTextHandler(Label control, string text);

    private void UpdateText(Label control, string text)

    {

    if (!control.InvokeRequired)

    control.Text = text;

    else

    {

    UpdateTextHandler handler = new UpdateTextHandler(UpdateText);

    control.BeginInvoke(handler, new

    object[] { control, text });

    }

    }



  • detecting multiple keys press