none
在线程中的类中操作窗体中的控件? RRS feed

  • 问题

  • 代码如下:

     

    Public Class Form1
        Delegate Sub SetTextCallback(ByVal [text] As String)
        Private demoThread As Thread = Nothing
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Me.demoThread = New Thread( _
            New ThreadStart(AddressOf Me.ThreadProcUnsafe))

            Me.demoThread.Start()
        End Sub
        Private Sub ThreadProcUnsafe()
            Dim a As New cc
            a.SetText("This text was set safely.")
        End Sub
        Class cc
            Public Sub SetText(ByVal [text] As String)
                If Form1.TextBox1.InvokeRequired Then
                    Dim d As New SetTextCallback(AddressOf SetText)
                    Form1.Invoke(d, New Object() {[text]})
                Else
                    Form1.TextBox1.Text = [text]
                End If
            End Sub
        End Class
    End Class

     

    执行以后,窗体中的文本框中的文本没有变化?

     

    在运行的时候也没报错,语句执行后为什么反应呢???

     

     

    2008年6月11日 2:48

答案

  •  

    Code Snippet

    Delegate Sub SetTextCallback(ByVal frm As Form1, ByVal [text] As String)

     

     

    Code Snippet

     

    a.SetText(Me, "This text was set safely.")

     

     

    Code Snippet

     

    Public Sub SetText(ByVal frm As Form1, ByVal [text] As String)
            If frm.InvokeRequired Then
                Dim d As New SetTextCallback(AddressOf SetText)
                frm.Invoke(d, New Object() {frm, [text]})
            Else
                frm.TextBox1.Text = [text]
            End If
        End Sub

     

     

     

    2008年6月13日 3:32
    版主

全部回复

  •  

    Code Snippet

    Delegate Sub SetTextCallback(ByVal frm As Form1, ByVal [text] As String)

     

     

    Code Snippet

     

    a.SetText(Me, "This text was set safely.")

     

     

    Code Snippet

     

    Public Sub SetText(ByVal frm As Form1, ByVal [text] As String)
            If frm.InvokeRequired Then
                Dim d As New SetTextCallback(AddressOf SetText)
                frm.Invoke(d, New Object() {frm, [text]})
            Else
                frm.TextBox1.Text = [text]
            End If
        End Sub

     

     

     

    2008年6月13日 3:32
    版主
  • 在同一个类中我也能实现,但在不同类中就不行,但我已经找到了原因,因为在不同的类中只能访问shared成员!

    2008年6月14日 7:02