繁体   English   中英

Winform C#中的关键事件问题

[英]Key event issue in winform c#

在我的项目中,我需要修改此预制代码以更改游戏的布局。 因此,我想在表单上添加按键事件以导航到“ WASD”,而不是使用按钮移动蛇。 但是这里的问题是,一旦我将函数添加到窗体中并对其进行测试以使其可以在控制台上显示出来,它什么也不会给出,而不是事件错误。 我不是专家,所以我希望有人能带领我走上正确的道路,谢谢。

这是我的项目的代码和屏幕截图。

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

表单的设计视图。 表单的设计视图

您的问题是通常Form上的Control之一将具有焦点并捕获所有关键事件。

为了使您的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