等到定时器结束,直到执行下一条指令

时间:2015-11-17 17:31:23

标签: c# winforms timer

背景:首先我知道我的一些代码很乱,请不要讨厌我。基本上我想在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);

1 个答案:

答案 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)完成。