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 ();
}
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]
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;
}
}
Left
Left
Right
Down
Up
Shift_R
Down
Left
Right
Up
Right
Up
Down
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With