【问题标题】:Sliding in Winforms form以 Winforms 形式滑动
【发布时间】:2010-03-23 19:07:55
【问题描述】:

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

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 - 有什么想法吗?

【问题讨论】:

  • @rs:我将“Winforms”放入标题中以区别于 WPF,并删除了 C#,因为它已经在标签中,也不应该出现在标题中。我使用了 WinForms 标签,因为这是您正在使用的技术。你出于某种原因反对吗?

标签: c# winforms loops


【解决方案1】:

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

【讨论】:

  • 有点老套,但我会试一试 :)
  • @rs - 不是 hacky,这是唯一的好方法。我很惊讶DoEvents 没用,但这确实是一件好事,因为DoEvents 非常糟糕。
【解决方案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();

【讨论】:

  • 这很好,但是即使我将睡眠值设置为 1,我发现它在旧机器上运行太慢了。如果它有一个总时间来完成动画并递增位置基于经过的时间量。
猜你喜欢
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
  • 2023-01-16
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多