0

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?

nalzok
  • 14,965
  • 21
  • 72
  • 139
Nulle
  • 1,301
  • 13
  • 28
  • 1
    What is your expected behaviour? Do you want to detect did user pressed Up and then Right? Or do you want to detect that keys are pressed at the same time? Please edit your question and put more details. Your example will not work because on key press event only one key is handled and you checking are 2 keys are pressed - this will never happen. – Renatas M. Jun 05 '17 at 13:20
  • keys pressed at the same time – Nulle Jun 05 '17 at 13:28
  • right now if you press up and right in my code then the action will be take for the key that was pressed first. I want it to take action for both. – Nulle Jun 05 '17 at 13:29
  • 1
    That isn't how GUI toolkits work. They will only send one key event per individual key, and you have to keep track of keys pressed and released in order to handle multiple keys pressed at the same time. Sorry. (*Modifier* keys are different because you can get information about them for every keypress, but the directional keys are not modifier keys.) Also, your compiler should have warned you that the `if` condition there will never be true; one variable cannot hold two distinct values at the same time. – andlabs Jun 05 '17 at 14:06

1 Answers1

1

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;
    }
}
Renatas M.
  • 11,694
  • 1
  • 43
  • 62