简体   繁体   中英

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. 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.

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:

public Form1()
{
    InitializeComponent();

    backgroundMusic.PlayLooping();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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