2010-03-23 61 views
4

我在屏幕的底部做一​​個形式,我希望它向上滑動,所以我寫了下面的代碼:中的WinForms形式滑動

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); 
} 

但代碼只是貫穿而顯示結束而不顯示滑動的形式,而這正是我想要的。我試過刷新,DoEvents - 任何想法?

+1

@rs:我將「Winforms」放入標題中以區別於WPF,並刪除了C#,因爲它已經存在於標記中,並且不應位於標題中。我使用了WinForms標籤,因爲這是您使用的技術。你有什麼理由反對嗎? – 2010-03-23 19:27:15

回答

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(); 
+0

工作完美 - 謝謝:D – 2010-03-23 19:23:32

+0

這很好,但我看到它在較老的機器上運行速度太慢,即使我將Sleep值設置爲1。如果它有完成動畫的總時間並且根據已經過的時間量增加位置。 – 2012-11-29 00:58:19

6

嘗試使用Timer事件而不是循環。

+0

有點哈克,但我會試試:) – 2010-03-23 19:11:21

+5

@rs - 不hacky,這是唯一的好方法。我很驚訝'DoEvents'不起作用,但真的這是一件好事,因爲'DoEvents'很嚴重。 – 2010-03-23 19:13:19