CSharp 定时器问题
CSharp Timer Problems
我的计时器没有按预期工作,为什么每次调用计时器间隔后图片框移动得更快。
我希望图片框在有人按下 D 按钮后在窗体上频繁移动。 add 和 remove Event 函数工作正常,所以不可能是这样:
Timer loop;
Int32 posX, posY;
public Form1()
{
InitializeComponent();
loop = new Timer();
}
private void Form1_Load(object sender, EventArgs e)
{
sprit.Enabled = false;
loop.Interval = 10;
posX = this.sprit.Location.X;
posY = this.sprit.Location.Y;
}
private void nextStep(object sender, EventArgs e)
{
posX++;
this.sprit.Location = new Point(posX, posY);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.D:
addEvent(nextStep);
loop.Start();
break;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.D:
removeEvent(nextStep);
loop.Stop();
break;
}
}
Form1_KeyDown
只要按住键就会重复调用,所以一直调用addEvent(nextStep)
.
尝试在 Form1_KeyDown
上仅调用一次 addEvent(nextStep)
我的计时器没有按预期工作,为什么每次调用计时器间隔后图片框移动得更快。
我希望图片框在有人按下 D 按钮后在窗体上频繁移动。 add 和 remove Event 函数工作正常,所以不可能是这样:
Timer loop;
Int32 posX, posY;
public Form1()
{
InitializeComponent();
loop = new Timer();
}
private void Form1_Load(object sender, EventArgs e)
{
sprit.Enabled = false;
loop.Interval = 10;
posX = this.sprit.Location.X;
posY = this.sprit.Location.Y;
}
private void nextStep(object sender, EventArgs e)
{
posX++;
this.sprit.Location = new Point(posX, posY);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.D:
addEvent(nextStep);
loop.Start();
break;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.D:
removeEvent(nextStep);
loop.Stop();
break;
}
}
Form1_KeyDown
只要按住键就会重复调用,所以一直调用addEvent(nextStep)
.
尝试在 Form1_KeyDown
addEvent(nextStep)