等待计时器结束,直到执行下一条指令
本文关键字:执行 一条 指令 计时器 结束 等待 | 更新日期: 2023-09-27 18:22:19
背景:首先,我知道我的一些代码很乱,请不要讨厌我。基本上,我想在Windows窗体窗口上为TextBox对象的移动设置动画。我已经通过使用Timer
成功地做到了这一点。然而,我的其余代码在计时器运行时执行(因此TextBox仍在移动)。我该如何阻止这种情况的发生。
这是我的一些代码:
move
方法:
private void move(int x, int y)
{
xValue = x;
yValue = y;
// Check to see if x co-ord needs moving up or down
if (xValue > txtData.Location.X) // UP
{
xDir = 1;
}
else if (xValue < box.Location.X) // DOWN
{
xDir = -1;
}
else // No change
{
.xDir = 0;
}
if (yValue > box.Location.Y) // RIGHT
{
yDir = 1;
}
else if (yValue < Location.Y) // LEFT
{
yDir = -1;
}
else // No change
{
yDir = 0;
}
timer.Start();
}
定时器Tick
方法:
private void timer_Tick(object sender, EventArgs e)
{
while (xValue != box.Location.X && yValue != box.Location.Y)
{
if (yDir == 0)
{
box.SetBounds(box.Location.X + xDir, box.Location.Y, box.Width, box.Height);
}
else
{
box.SetBounds(box.Location.X, box.Location.Y + yDir, box.Width, box.Height);
}
}
}
move
调用:
move(478, 267);
move(647, 267);
move(647, 257);
我不确定你到底在问什么,但如果你试图强制程序停止运行代码,直到动画完成,你可以尝试使用异步等待。不过,您至少需要.Net 4.5才能使用异步等待。
private async void moveData(int x, int y)
{
Variables.xValue = x;
Variables.yValue = y;
// Check to see if x co-ord needs moving up or down
if (Variables.xValue > txtData.Location.X) // UP
{
Variables.xDir = 1;
}
else if (Variables.xValue < txtData.Location.X) // DOWN
{
Variables.xDir = -1;
}
else // No change
{
Variables.xDir = 0;
}
// Check to see if y co-ord needs moving left or right
if (Variables.yValue > txtData.Location.Y) // RIGHT
{
Variables.yDir = 1;
}
else if (Variables.yValue < txtData.Location.Y) // LEFT
{
Variables.yDir = -1;
}
else // No change
{
Variables.yDir = 0;
}
await Animate();
}
private async Task Animate()
{
while (Variables.xValue != txtData.Location.X && Variables.yValue != txtData.Location.Y)
{
if (Variables.yDir == 0) // If we are moving in the x direction
{
txtData.SetBounds(txtData.Location.X + Variables.xDir, txtData.Location.Y, txtData.Width, txtData.Height);
}
else // We are moving in the y direction
{
txtData.SetBounds(txtData.Location.X, txtData.Location.Y + Variables.yDir, txtData.Width, txtData.Height);
}
await Task.Delay(intervalBetweenMovements);
}
}
这样,它将等待移动(x,y)完成,然后再移动到下一行。