2015-05-23 66 views
2

當前版本中只有一個按鈕閃爍。如何使用異步/等待任務動畫按鈕顏色?

主營:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace NEW_Flicker_Test_Async 
{ 
    public partial class Form1 : Form 
    { 
     async Task Flicker<T>(T target, TimeSpan time) where T : Control 
     { 
      for (var isWhite = true; ; isWhite = !isWhite) 
      { 
       target.BackColor = isWhite 
        ? System.Drawing.Color.White 
        : System.Drawing.Color.Black; 
       await Task.Delay(time); 
      } 
     } 

     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private async void Form1_Load(object sender, EventArgs e) 
     { 
      await Flicker(button1, TimeSpan.FromMilliseconds(83)); 
      await Flicker(button2, TimeSpan.FromMilliseconds(77)); 
      await Flicker(button3, TimeSpan.FromMilliseconds(71)); 
      await Flicker(button4, TimeSpan.FromMilliseconds(66)); 
      await Flicker(button5, TimeSpan.FromMilliseconds(61)); 

     } 
    } 
} 
+0

你看到了什麼,當你運行的程序?你期望看到什麼? – soegaard

+0

表單沒有啓動,它表示準備好但不打開表單,當我運行ot @ soegaard時,我想在屏幕上閃爍的按鈕。 –

+0

@soegaard現在的形式和類都在上面。 –

回答

1
using System; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

class FlickerForm 
{ 
    public static void Execute() 
    { 
    var button = new Button { Width = 200, Height = 30, Text = "Test" }; 
    var button2 = new Button { Width = 200, Height = 30, Top = 30, Text = "Test2" }; 
    var form = new Form { Width = 800, Height = 600, Controls = { button, button2 } }; 

    form.Load += async (_s, _e) => await Task.WhenAll 
    (
     Flicker(button, TimeSpan.FromSeconds(2)), 
     Flicker(button2, TimeSpan.FromSeconds(3)) 
    ); 

    Application.Run(form); 
    } 

    static async Task Flicker<T>(T target, TimeSpan period) where T:Control 
    { 
    for (var isWhite = false; ; isWhite = !isWhite) 
    { 
     target.BackColor = isWhite ? System.Drawing.Color.White : System.Drawing.Color.Black; 
     await Task.Delay(period); 
    } 
    } 
} 
+0

我應該如何實現這個?,這是一個自我形式或形式的類嗎? –

+0

@AslakAøgaard這是一個完整的例子。在你的代碼實現方法閃爍和閃爍調用。 –

+0

如果我需要更多按鈕以及不同的時間跨度,該怎麼辦? –