0

いろいろな投稿を読んで、練習プロジェクトを作ったのですが、うまくいきません。フォームにはボタンとテキスト ボックスがあり、既定のテキストは「更新回数 0 回」です。ボタンをクリックするとタイマーが開始され、そのたびにテキストが更新された回数でテキストが更新されます。

クロス スレッド呼び出しの例外はスローされませんが、テキスト ボックスを呼び出すと、その .Text = ""、テキストは更新されますが、フォーム上のテキスト ボックスは更新されません。InvokeRequired は常に false です。

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