繁体   English   中英

使用计时器更新表格-VB.Net

[英]Using a timer to update form - VB.Net

我想在表单上显示应用程序各方面的状态。

我尝试将计时器添加到表单。 计时器每隔10秒运行一次,并检查数据库的特定状态,然后根据状态更改表单上的元素。

这对于更改菜单项的颜色效果很好,但是当我尝试使图像在窗体上不可见时,我遇到了跨线程错误。

我应该使用计时器,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

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM