簡體   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