繁体   English   中英

如何在Gtk#C#中手动检测箭头键

[英]How to manually detect arrow keys in gtk# c#

我正在尝试使用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 ();
}

您需要做的就是添加您的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM