【问题标题】:Using a timer to update form - VB.Net使用计时器更新表单 - VB.Net
【发布时间】:2014-02-11 10:10:38
【问题描述】:

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

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

这适用于更改菜单项的颜色,但是当我尝试使图像在表单上(不)可见时,我得到一个跨线程错误。

我应该使用计时器、Backgroundworker 还是其他东西?

有人有一些基本的代码可以优雅地做到这一点吗?

Private 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

【问题讨论】:

  • 你能提供一些代码吗?
  • 添加的代码非常基本,但应该会给您一些想法。

标签: vb.net multithreading forms timer


【解决方案1】:

试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多