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

时间:2019-02-03 18:10:47

标签: c# keyevent

我正在制作一个C#WFA游戏引擎,从一个空的VS项目/重新构建它。我已经到达需要添加输入的位置,但是不知道如何添加keyDown / keyUp事件,也不知道如何添加或使用KeyEventHandler。对不起,我的英语。

我尝试使用引用From类的局部类,但这无济于事。我从根本上被困住了,而且我已经研究过并且一直无法找到任何东西。

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

}

1 个答案:

答案 0 :(得分:0)

  

如果是游戏引擎,您可能实际上想钩住键盘,无论如何,对于按键处理程序,您基本上都会创建一个委托,因此OnKeyPressed + =(双击选项卡可在VS中自动创建委托)

反复试验后,我开始尝试

public void addInstrumentPrice(ip){
   instrumentPriceList.add(ip);
   ip.setInstrument(this);
}