以Winforms形式滑动

时间:2010-03-23 19:07:56

标签: c# winforms loops

我正在屏幕底部制作一个表单,我希望它向上滑动,所以我写了下面的代码:

int destinationX = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (this.Width / 2);
int destinationY = Screen.PrimaryScreen.WorkingArea.Height - this.Height;

this.Location = new Point(destinationX, destinationY + this.Height);

while (this.Location != new Point(destinationX, destinationY))
{
    this.Location = new Point(destinationX, this.Location.Y - 1);
    System.Threading.Thread.Sleep(100);
}

但代码只是贯穿并显示结束位置而没有显示表单滑动,这就是我想要的。我尝试过Refresh,DoEvents - 有什么想法吗?

2 个答案:

答案 0 :(得分:7)

尝试使用Timer事件而不是循环。

答案 1 :(得分:2)

在后台线程中运行代码。例如:

        int destinationX = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (this.Width / 2);
        int destinationY = Screen.PrimaryScreen.WorkingArea.Height - this.Height;

        Point newLocation = new Point(destinationX, destinationY + this.Height);

        new Thread(new ThreadStart(() =>
        {
            do
            {
                 // this line needs to be executed in the UI thread, hence we use Invoke
                this.Invoke(new Action(() => { this.Location = newLocation; }));

                newLocation = new Point(destinationX, newLocation.Y - 1);
                Thread.Sleep(100);
            }
            while (newLocation != new Point(destinationX, destinationY));
        })).Start();