Search code examples
c#gtkkeypressgdk

C# KeyPressEventArgs Multiple Keypress


Using KeyPressEventArgs I want to be able to detect multiple keypresses. I have tried it like this without luck.

[GLib.ConnectBefore]
public override void OnKeyPress (object o, global::Gtk.KeyPressEventArgs args)
{ 
  if ((args.Event.Key == Gdk.Key.Up) && (args.Event.Key == Gdk.Key.Right)) 
  {
      playerPhysics.AddVector (_taxiGoUp);
      Player._state = Taxi.State.MoveUp;   
      playerPhysics.AddVector (_taxiGoRight);
      Player._state = Taxi.State.MoveRight;
  }
}

Can anyone help figuring this out?


Solution

  • You should handle key down and up events in your case. Here is code for basic idea how you could do it:

    bool keyRight = false;
    bool keyUp = false;
    
    [GLib.ConnectBefore]
    public override void OnKeyDown (object o, global::Gtk.KeyDownEventArgs args)
    { 
        switch (args.Event.Key) 
        {
           case Gdk.Key.Up:
             if(!keyUp)
             {
                keyUp = true;
                playerPhysics.AddVector (_taxiGoUp);
                Player._state = Taxi.State.MoveUp;            
             }
             break;
           case Gdk.Key.Right:
             if(!keyRight)
             {
                keyRight = true;
                playerPhysics.AddVector (_taxiGoRight);
                Player._state = Taxi.State.MoveRight;            
             }
             break;
        }
    }
    
    [GLib.ConnectBefore]
    public override void OnKeyDown (object o, global::Gtk.KeyUpEventArgs args)
    { 
        switch (args.Event.Key) 
        {
           case Gdk.Key.Up:
             keyUp = false;
             break;
           case Gdk.Key.Right:
             keyRight = false;
             break;
        }
    }