0

我阅读了各种帖子,并做了一个练习项目,但它不起作用。该表单有一个按钮和一个带有默认文本“更新 0 次”的文本框。在按钮单击时启动计时器,并且每次使用文本更新的次数更新文本。

不抛出跨线程调用的异常,但是在调用文本框时,其.Text = "",更新的是文本而不是窗体上的文本框。并且 InvokeRequired 始终为假。

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Here the textBox.Text = "Updated 0 times."
    Dim checking_text As String = Me.TextBox1.Text
    TimerTest.StartTimer()
End Sub


Delegate Sub UpdateTextInvoke(ByVal new_text As String)
Public Sub UpdateText(ByVal new_text As String)
    'Here the textBox.Text = ""
    Dim txtB As TextBox = Me.TextBox1
    'InvokeRequired always = False.
    If txtB.InvokeRequired Then
        Dim invk As New UpdateTextInvoke(AddressOf UpdateText)
        txtB.Invoke(invk, New Object() {new_text})
    Else
        'The value of this text box is updated, but the text on the form TextBox1 never changes
        txtB.Text = new_text
    End If
End Sub
End Class


Public Class TimerTest
Private Shared tmr As New System.Timers.Timer
Private Shared counter As Integer

Public Shared Sub StartTimer()
    tmr.Interval = 5000
    AddHandler tmr.Elapsed, AddressOf UdpateText
    tmr.Enabled = True
End Sub

Public Shared Sub UdpateText(ByVal sender As Object, ByVal e As System.EventArgs)
    counter += 1
    Form1.UpdateText(String.Format("Updated {0} time(s).", counter))
End Sub
End Class

已解决在 TimerTest 类中添加了此代码“Private Shared myform As Form1 = Form1”,然后将“Form1.UpdateText”更改为“myform.UpdateText”

4

1 回答 1

1

如评论中所示,您正在使用 VB.Net 的默认表单实例功能。您可以将表单的一个实例传递给 TimerTest 类,并将对 Form1 的引用替换为该实例。

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim checking_text As String = Me.TextBox1.Text
        TimerTest.StartTimer(Me)
    End Sub
    Public Sub UpdateText(new_text As String)
        If TextBox1.InvokeRequired Then
            Dim invk As New Action(Of String)(AddressOf UpdateText)
        TextBox1.Invoke(invk, {new_text})
    Else
            TextBox1.Text = new_text
        End If
    End Sub
End Class

Public Class TimerTest
    Private Shared tmr As New System.Timers.Timer()
    Private Shared counter As Integer
    Private Shared instance As Form1

    Public Shared Sub StartTimer(formInstance As Form1)
        instance = formInstance
        tmr.Interval = 5000
        AddHandler tmr.Elapsed, AddressOf UdpateText
        tmr.Enabled = True
    End Sub

    Public Shared Sub UdpateText(ByVal sender As Object, ByVal e As System.EventArgs)
        counter += 1
        instance.UpdateText(String.Format("Updated {0} time(s).", counter))
    End Sub
End Class
于 2018-07-10T20:52:13.930 回答