背景:首先我知道我的一些代码很乱,请不要讨厌我。基本上我想在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);
答案 0 :(得分:1)
我不确定你要问的是什么,但如果你试图强制程序在动画完成之前停止运行代码,你可以尝试使用async await。但是,至少需要.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);
}
}
这样它会在移动到下一行之前等待move(x,y)完成。