如何在gtk#c#

时间:2016-03-06 22:54:08

标签: c# monodevelop gtk#

我正在尝试使用Gtk#-C#在Monodevelop中制作游戏,其中玩家使用箭头键移动角色。但是,箭头键按下没有注册。

有没有办法手动检测按键,绕过默认处理程序?

Google和Stack Overflow上的多次搜索都没有给出如何使用Gtk-C#检测箭头键的答案。

这是我用来尝试检测箭头键的代码:

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);
}

这是我试图弄清楚如何检测箭头键的基本程序:

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 ();
}

1 个答案:

答案 0 :(得分:4)

您需要做的就是像这样添加KeyPress处理程序:

KeyPressEvent += KeyPress;

并将GLib.ConnectBefore属性添加到您的事件中,以便在应用程序处理程序使用它之前收到它:

[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
相关问题