2011-05-29 110 views
37

我有用C#編寫的Windows窗體應用程序。以下功能檢查打印機是否聯機:每X秒執行指定的函數

public void isonline() 
{ 
    PrinterSettings settings = new PrinterSettings(); 
    if (CheckPrinter(settings.PrinterName) == "offline") 
    { 
     pictureBox1.Image = pictureBox1.ErrorImage; 
    } 
} 

並更新圖像,如果打印機處於脫機狀態。現在,我怎樣才能每2秒鐘執行一次isonline()這樣的功能,所以當我拔下打印機時,表格(pictureBox1)上顯示的圖像會變成另一個圖像,而無需重新啓動應用程序或進行手動檢查? (例如通過按下運行isonline()功能的「刷新」按鈕)

+6

輪詢是不是一個好主意。如果存在狀態更改通知,最好傾聽。 – 2011-05-29 17:50:51

+1

[在c#中執行一個操作,每隔x秒鐘執行一個操作](http://stackoverflow.com/questions/786672/execute-an-operation-every-x-seconds-for-y-minutes-in- c) – 2011-05-29 17:50:56

回答

78

使用System.Windows.Forms.Timer

private Timer timer1; 
public void InitTimer() 
{ 
    timer1 = new Timer(); 
    timer1.Tick += new EventHandler(timer1_Tick); 
    timer1.Interval = 2000; // in miliseconds 
    timer1.Start(); 
} 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    isonline(); 
} 

可以在Form1_Load()調用InitTimer()

+0

這只是工作。非常感謝。 – technology 2011-05-29 17:47:48

+0

這會在應用程序啓動後自動執行嗎?這不適合我。你能提出一些解決方案嗎?謝謝 – user2886091 2014-03-19 08:06:13

+0

@ user2886091:只要定時器不處理或停止,它應該可以工作 – Stecya 2014-03-19 10:21:32

3

您可以通過在窗體中添加一個Timer(來自設計者)並將其設置爲Tick函數來運行isonline函數,從而輕鬆完成此操作。

5

最適合初學者的解決方案是:

從工具箱拖一個計時器,給它一個名稱,設置所需的時間間隔,並設置爲「Enabled」爲True。然後雙擊計時器和Visual Studio(或任何你正在使用的)會寫你下面的代碼:

private void wait_Tick(object sender, EventArgs e) 
    { 
     refreshText(); //add the method you want to call here. 
    } 

那裏你去。無需擔心將其粘貼到錯誤的代碼塊或類似的東西。

0

我已經上傳了一個NuGet包,可以使如此簡單,你可以從這裏OpenJobScheduler

這裏有它如何開始使用它

using OpenJobScheduler; 

var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => { 
    //What you want to execute 
})); 

jobScheduler.Start(); // To Start up the Scheduler 

jobScheduler.Stop(); // To Stop Scheduler from Running. 
+0

你好,試着安裝nuget,但它不適用於.NET 4.5.2,它的版本是什麼? – avechuche 2017-12-05 16:16:46

+1

它支持.NET標準2.0 – 2017-12-05 19:00:17

+1

@avechuche所以它支持.NET 4.6.1及以上版本 – 2017-12-05 20:16:00