2009-02-06 85 views
1

我只是增加了一些額外的功能Coding4Fun項目。我有我的項目設置了一個額外的選項,以允許它在X時間後自動更改背景。 X從ComboBox中設置。然而,我知道我已經以可怕的方式完成了這個任務,因爲我已經創建了一個System.Timers.Timer作爲父類的新計時器類,因此當調用ElapsedEventHandler中的靜態方法時,我可以返回窗體並調用ChangeDesktopBackground()。計時器上的壁紙循環器

什麼是以用戶定義的間隔調用ChangeDesktopBackground()的更好方法?

這是我目前的解決方案,它涉及到將發件人轉換爲我的繼承計時器,然後它獲得對錶單的引用,然後調用ChangeDesktopBackground方法。

private static void timerEvent(object sender, System.Timers.ElapsedEventArgs e) 
{ 
    ((newTimer)sender).getCycleSettingsForm().ChangeDesktopBackground(); 
} 

編輯:新增編碼樣本顯示當前的解決方案

回答

0

定時器可能是這樣做的最直接的方式,雖然我不知道你正確使用定時器。下面是我用定時器在我的項目:

// here we declare the timer that this class will use. 
private Timer timer; 

//I've shown the timer creation inside the constructor of a main form, 
//but it may be done elsewhere depending on your needs 
public Main() 
{ 

    // other init stuff omitted 

    timer = new Timer();  
    timer.Interval = 10000; // 10 seconds between images 
    timer.Tick += timer_Tick; // attach the event handler (defined below) 
} 


void timer_Tick(object sender, EventArgs e) 
{ 
    // this is where you'd show your next image  
} 

然後,您可以連接您的組合框onChange處理,使得你會改變timer.Interval。

0

我以前寫過類似的東西。 System.Timers.Timer對此是矯枉過正的。您應該使用System.Windows.Forms.Timer,原因如下:

  1. 您正在做的事情不必太精確。 Windows定時器只是一個WM_TIMER消息發送到你的Windows應用程序的消息泵,所以你沒有得到超級高精度,但每秒更換一次壁紙是不現實的。 (我寫我的每6小時左右更換一次)
  2. 當使用Windows窗體應用程序執行某種基於計時器的任務時,如果使用System,您將遇到各種線程關聯問題。 Timers.Timer。任何Windows控件對創建它的線程都有親和力,這意味着您只能修改該線程上的控件。 Windows.Forms.Timer將爲你做所有這些事情。 (對於未來的nitpickers,更換壁紙並不真正算,因爲它是註冊表值的變化,但規則通常是成立的)
0

我會爲此使用Microsoft的Reactive Framework。只是NuGet「Rx-WinForms」。

下面的代碼:

var subscription = 
    Observable 
     .Interval(TimeSpan.FromMinutes(1.0)) 
     .ObserveOn(this) 
     .Subscribe(n => this.getCycleSettingsForm().ChangeDesktopBackground()); 

要停止它只是做subscription.Dispose()

簡單。