2014-02-11 68 views
0

我想在窗體上顯示我的應用程序的各個方面的狀態。使用計時器更新表單 - VB.Net

我試着給窗體添加一個計時器。計時器每10秒鐘運行一次並檢查數據庫是否有特定狀態,然後根據狀態更改表單上的元素。

這適用於更改菜單項的顏色,但是當我嘗試使圖像(in)在窗體上可見時,出現跨線程錯誤。

我應該使用計時器,Backgroundworker還是其他?

有人有一個基本的代碼將優雅地做到這一點?

私人WITHEVENTS tmrMain作爲新System.Timers.Timer(10000)

Private Sub frmMaster_Load(sender As Object, e As EventArgs) Handles Me.Load 
    tmrMain.Enabled = True 
    tmrMain.Start() 
End Sub 

Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed 
    Dim TRunning As Boolean = True 

     TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB 

     If TRunning Then 
      miFileMYOBImport.ForeColor = Color.Red '' Change menu color 
      pbMYOBDownload.Visible = True '' Make image visible 
     Else 
      miFileMYOBImport.ForeColor = Color.DarkGreen 
      pbMYOBDownload.Visible = False 
     End If 
End Sub 
+0

你能否提供一些代碼? –

+0

添加的代碼是非常基本的,但應該給你的想法。 – AlMacOwl

回答

0

嘗試:

Private Sub MakeImageVisible(ByVal control As Control, ByVal visible As Boolean) 
    If control.InvokeRequired Then 
     control.BeginInvoke(New Action(Of Control, Boolean)(AddressOf MakeImageVisible), control, visible) 
    Else 
     control.Visible = visible 
    End If 
End Sub 

Private Sub tmrMain_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmrMain.Elapsed 
    Dim TRunning As Boolean = True 

    TRunning = BTools.CheckImportRunningStatus '' This gets the on/off status from the DB 

    If TRunning Then 
     miFileMYOBImport.ForeColor = Color.Red '' Change menu color 
    Else 
     miFileMYOBImport.ForeColor = Color.DarkGreen 
    End If 

    MakeImageVisible(pbMYOBDownload, TRunning) ' Make image visible or invisible 
End Sub