วิธีตรวจจับปุ่มลูกศรด้วยตนเองใน gtk# c#

ฉันกำลังพยายามสร้างเกมใน Monodevelop โดยใช้ Gtk#-C# โดยให้ผู้เล่นเคลื่อนตัวละครไปรอบๆ ด้วยปุ่มลูกศร อย่างไรก็ตาม การกดปุ่มลูกศรไม่ได้ถูกลงทะเบียน

มีวิธีตรวจจับการกดปุ่มด้วยตนเองโดยข้ามตัวจัดการเริ่มต้นหรือไม่

การค้นหาหลายครั้งทั้งบน 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 ();
}

person Rene    schedule 06.03.2016    source แหล่งที่มา


คำตอบ (1)


สิ่งที่คุณต้องทำคือเพิ่มตัวจัดการ 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
person SushiHangover    schedule 07.03.2016
comment
ฉันกำลังมองหาอย่างอื่น แต่วิธีนี้ช่วยแก้ไขปัญหาอื่นได้ ขอบคุณ - person Madivad; 31.07.2018