如何在空 C# 项目上添加/使用 KeyEventHandler

How to add / use a KeyEventHandler on to a empty C# project

我正在制作一个 C# WFA 游戏引擎,从一个空的 VS 项目/开始构建它。我已经到了需要添加输入但不知道如何添加 keyDown / keyUp 事件,也不知道如何添加或使用 KeyEventHandler 的地步。请原谅我的英语。

我试过使用部分 class 引用 From class 但它没有帮助。我基本上被卡住了,我已经研究过但本找不到任何东西。

class Window
{
    // privates needed to intialize the game screen
    private Form screen;
    private Size size;
    private Bitmap bitmap;
    private Graphics LoadGraphics;
    private Graphics FinalGraphics;

    // constructor for the window / game screen
    public Window(GameContainer gc)
    {
        // initializes the game screen
        bitmap = new Bitmap(gc.GetWidth(), gc.GetHeight());
        size = new Size((int)(gc.GetWidth() * gc.GetScale()), (int) 
                         (gc.GetHeight() * gc.GetScale()));
        screen = new Form();

        // makes the Game screen not resizeable 
        screen.GetPreferredSize(size);
        screen.MinimumSize = size;
        screen.MaximumSize = size;
        screen.Size = size;
        screen.FormBorderStyle = FormBorderStyle.FixedToolWindow;

        screen.Text = gc.GetTitle();

        // intializes the graphics
        LoadGraphics = screen.CreateGraphics();
        FinalGraphics = screen.CreateGraphics();
        screen.BackColor = Color.Black;
    }

    // updater for the game screen
    public void Update()
    { 
        Application.DoEvents();
        LoadGraphics = Graphics.FromImage(bitmap);
        FinalGraphics.DrawImage(bitmap, 0, 0, screen.Width, screen.Height);
        screen.Show();

    }

    // getter for the screen
    public Form GetScreen()
    {
        return screen;
    }

    // getter for the bitmap
    public Bitmap GetBitmap()
    {
        return bitmap;
    }

    public Color GetBackcolor()
    {
        return screen.BackColor;
    }
}

class Input
{
    public Input(Window screen)
    {
        screen.GetScreen().KeyPreview = true;
    }

    void Screen_KeyPress( object sender, KeyPressEventArgs e )
    {
        if (e.KeyChar == 65)
        {
            Console.WriteLine("you pressed A");
        }
    }

}

If it's game engine you may want to actually hook the keyboard, anyway for key handlers you basically create a delegate, so OnKeyPressed += (double click tab to autocreate delegate in VS)

经过反复试验,我成功了

public Input(Window screen)
{
    screen.GetScreen().KeyPreview = true;
    screen.GetScreen().KeyDown += Input_KeyDown;
}

private void Input_KeyDown( object sender, KeyEventArgs e )
{
    if(e.KeyCode == Keys.A)
    {
        Console.WriteLine("you pressed 'A' !");
    }
}