KeyDown函数未激活

时间:2016-01-31 22:08:32

标签: c#

我一直在做一个叫做狗模拟器的游戏。我在运动需要发展的地方,但由于某种原因,该功能没有激活。 Visual Studio(我使用的IDE)说没有错误。一些帮助将不胜感激

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dog_simulator
{

    public partial class Form1 : Form
    {
        bool right;
        bool left;
        public int left_var = 5;
        public int right_var = 5;

        public Form1()
        {

            InitializeComponent();

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        public void button2_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        public void button1_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        public void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine("Left has been pressed");
            if (e.KeyCode == Keys.Left)
            {
                left = true;
                Console.WriteLine("Left has been pressed");
            }
            if(e.KeyCode == Keys.Right)
            {
                right = true;
                Console.WriteLine("Right has been pressed");
            }
        }

        public void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                left = false;
                Console.WriteLine("Left has been let go of");
            }
            if (e.KeyCode == Keys.Right)
            {
                right = false;
                Console.WriteLine("Right has been let go of");
            }
        }

        public void timer1_Tick(object sender, EventArgs e)
        {
            if (right == true)
            {
                player.Left += left_var;

            }
            if (left == true)
            {
                player.Left -= left_var;
            }
            Invalidate();
        }

        private void dog_Click(object sender, EventArgs e)
        {

        }

        private void player_Click(object sender, EventArgs e)
        {

        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:2)

要使Windows窗体能够看到按下的键,您需要设置

this.KeyPreview = true;

在设计师或表单代码中。否则,按键将由具有当前焦点的控件接收。

MSDN:Form.KeyPreview