2017-05-26 29 views
1

當雙擊Form1時,會有一個代碼激活動畫。通過雙擊ListBox組件觸發動畫是必要的。如何改變?當用戶雙擊Windows窗體列表框時,如何觸發動畫開始?

public partial class Form1 : Form 
{ 
    Timer tmr; 
    public Form1() 
    { 
     InitializeComponent(); 
     this.MouseDoubleClick += Form1_MouseDoubleClick; 
     this.Paint += Form1_Paint; 
     tmr = new Timer(); 
     tmr.Interval = 10; 
     tmr.Tick += tmr_Tick; 
    } 

    int x; 
    int step = 5; 
    void Form1_MouseDoubleClick(object sender, MouseEventArgs e) 
    { 
     tmr.Stop(); 
     x = 0; 
     tmr.Start(); 
    } 

    void tmr_Tick(object sender, EventArgs e) 
    { 
     x += step; 
     if (x > this.Width) 
     { 
      x = 0; 
      (sender as Timer).Stop(); 
     } 
     this.Invalidate(); 
    } 
    void Form1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.FillRectangle(Brushes.Red, 0, 0, x, 4); 
    } 

} 
+0

對於處理'ListBox'控件上的雙擊事件,您可能希望看到[此問題](https://stackoverflow.com/questions/4454423/c-sharp-listbox-item-double-click -事件)。然後,更改上面的代碼以將此事件處理程序附加到您的「ListBox」控件而不是「Form1」。 –

回答

0

您需要啓動定時器:

tmr = new Timer(); 
tmr.Interval = 10; 
tmr.Tick += tmr_Tick; 
tmr.Start(); 

此外,形式並不需要聽自己的事件,你可以簡單地覆蓋的方法:

// this.Paint += Form1_Paint; 

protected override void OnPaint(PaintEventArgs e) { 
    e.Graphics.FillRectangle(Brushes.Red, 0, 0, x, 4); 
} 

考慮將您的窗體的DoubleBuffered屬性設置爲true,因爲您正在繪製該容器。

+0

我不明白。你能創建一個項目併發送給我嗎?抱歉。 – Gif

+0

@Gif理解什麼?我添加了一行代碼。如果您不理解,可以忽略事件/重寫問題。 – LarsTech

+0

我明白了。還有一個問題。我怎樣才能讓這個動畫不僅在頂部,而且在左側,右側和底部? – Gif

相關問題