简体   繁体   English

Winform C#中的关键事件问题

[英]Key event issue in winform c#

in my project i need to modified this pre-made code to change the layout of the game. 在我的项目中,我需要修改此预制代码以更改游戏的布局。 So i want to add key events on my form for my navigation to 'WASD' instead of using a button to move the snake. 因此,我想在表单上添加按键事件以导航到“ WASD”,而不是使用按钮移动蛇。 But the problem here is that once i added the function to the form and test it to display on the console out, it gives nothing, not event error. 但是这里的问题是,一旦我将函数添加到窗体中并对其进行测试以使其可以在控制台上显示出来,它什么也不会给出,而不是事件错误。 I am no expert in this, so i hope someone kind enough to lead me to the right path, thanks. 我不是专家,所以我希望有人能带领我走上正确的道路,谢谢。

This is the code and screenshot of my project. 这是我的项目的代码和屏幕截图。

public Form1()
    {
        InitializeComponent();

        backgroundMusic.PlayLooping();


        this.AutoSize = true;
        boardPanel.AutoSize = true;

        //Set up the main board
        mainBoard = new Board(this);

        //Set up the game timer at the given speed
        clock = new Timer();
        clock.Interval = speed; //Set the clock to tick every 500ms
        clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake.

        duration = 0;
        score = 0;
        level = 1;
        modeLBL.Text = mode;

        gotoNextLevel(level);

    }

    private void keyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.W)
        {
            Console.WriteLine("W is pressed");
        }
    }
}

Design View of the form. 表单的设计视图。 表单的设计视图

Your problem is that normally one of the Control s on your Form will have the focus and capture all key events. 您的问题是通常Form上的Control之一将具有焦点并捕获所有关键事件。

To enable your Form raise a KeyDown event when a key is pressed while a child control has the focus, set the KeyPreview property of your Form to true: 为了使您的Form筹集KeyDown事件时,而子控件具有焦点按下一个键时,设定KeyPreview你的财产Form为true:

public Form1()
{
    InitializeComponent();

    backgroundMusic.PlayLooping();

    this.AutoSize = true;
    this.KeyPreview = true; // <-- add this line

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

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