最近C#课程设计,打算做一个类是“玩个球”的小游戏(不是我想的,入错队伍坑了),我就想通过按键来控制“球”的移动,今天就试着实现一下按键监听的操作,搜了网上一大堆,耗时1个半终于弄出来了,不容易(网络上挺多忽悠的)。
一、首先创建一个叫Form1的窗体
二、点击窗体,然后到属性栏中双击KeyDown这个事件,会自动生成代码框架
三、把KeyPreview选为True
四、代码,实现按一下空格,静态整形变量count加一并于标签label2显示
-
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
WindowsFormsApplication5
-
{
-
public
partial
class
Form1 :
Form
-
{
-
static
int count =
0;
-
public Form1()
-
{
-
InitializeComponent();
-
}
-
-
private void Form1_Load(object sender, EventArgs e)
-
{
-
// this.KeyPreview = true; //第三步不选true也可以,但要在这里添加一段代码
-
}
-
-
private void Form1_KeyDown(object sender, KeyEventArgs e) //刚才双击产生的KeyDown事件的代码框架
-
{
-
if(e.KeyCode==Keys.Space)
-
{
-
count++;
-
label2.Text = count.ToString();
-
}
-
}
-
-
-
}
-
}