按键功能未激活

本文关键字:激活 功能 | 更新日期: 2023-09-27 18:32:44

我一直在做一款叫做狗模拟器的游戏。我正处于需要开发机芯的位置,但是,由于某种原因,该功能没有激活。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)
        {
        }
    }
}

按键功能未激活

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

this.KeyPreview = true;

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

MSDN: Form.KeyPreview