Search code examples
c#monodevelopgtk#

How to manually detect arrow keys in gtk# c#


I am trying to make a game in Monodevelop using Gtk#-C# where the player moves a character around with arrow keys. However, arrow key presses are not being registered.

Is there a way to manually detect key presses, bypassing the default handler?

Multiple searches on both Google and Stack Overflow have not given an answer as to how to detect arrow keys using Gtk-C#.

This is the code I've been using to try and detect the arrow keys:

protected void Key_Press (object obj, KeyPressEventArgs args)
{
    //Let the rest of the program know what keys were pressed.
    if (pressedKeys.Contains (args.Event.Key))
        return;
    pressedKeys.Add (args.Event.Key, args.Event.Key);
}

And here is a basic program I made to attempt to figure out how to detect arrow keys:

public MainWindow (): base (Gtk.WindowType.Toplevel)
{
    Build ();

    this.KeyPressEvent += new KeyPressEventHandler (KeyPress);
}

protected void KeyPress (object sender, KeyPressEventArgs args)
{
    if (args.Event.Key == Gdk.Key.Up)
        return;

    label1.Text = args.Event.Key.ToString ();
}

Solution

  • All you need to do is add your KeyPress handler like this:

    KeyPressEvent += KeyPress;
    

    And add the GLib.ConnectBefore attribute to your event so you receive it before the application handler consumes it:

    [GLib.ConnectBefore]
    

    Cut/Paste example:

    using System;
    using Gtk;
    
    public partial class MainWindow : Gtk.Window
    {
        public MainWindow() : base(Gtk.WindowType.Toplevel)
        {
            Build();
            KeyPressEvent += KeyPress;
        }
    
        [GLib.ConnectBefore]
        protected void KeyPress(object sender, KeyPressEventArgs args)
        {
            Console.WriteLine(args.Event.Key);
        }
    
        protected void OnDeleteEvent(object sender, DeleteEventArgs a)
        {
            KeyPressEvent -= KeyPress;
            Application.Quit();
            a.RetVal = true;
        }
    }
    

    Example Output:

    Left
    Left
    Right
    Down
    Up
    Shift_R
    Down
    Left
    Right
    Up
    Right
    Up
    Down