当前位置: 代码迷 >> VB Dotnet >> 跨线程访问界面控件,在模块中不行!该怎么解决
  详细解决方案

跨线程访问界面控件,在模块中不行!该怎么解决

热度:65   发布时间:2016-04-25 02:05:15.0
跨线程访问界面控件,在模块中不行!!!!!!!!!!
跨线程访问界面控件时,需要使用委托,如果所有的定义和函数都放在窗体的代码文件中(即:form1.vb)可以正常运行,主要代码如下:

 Public Delegate Sub voiddelegate(ByRef Obj As Object, ByVal Str As String)
 Private Shared aTimer As System.Timers.Timer
  Dim i As Integer
  Dim j As Integer
  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    aTimer = New System.Timers.Timer(10)
     AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
    aTimer.Enabled = True
    End Sub

 Private Sub OnTimedEvent()
    aTimer.Enabled = False  
      i = (i + 1)
       If Label1.InvokeRequired Then
        Me.BeginInvoke(New voiddelegate(AddressOf UpdateUI), Label1, i.ToString)
      Else
        Label1.Text = i
      End If
   
    aTimer.Enabled = True
  End Sub

 Public Sub UpdateUI(ByRef Obj As Object, ByVal Str As String)
    Obj.text = Str
      End Sub


这样运行没有问题。但是将委托的定义、OnTimedEvent函数、UpdateUI函数放到module1.vb模块中, Me.BeginInvoke,改为form1.BeginInvoke。就不行了。也不报错,但是label1.text不会变化了。
难道只能将所有的定义和函数放到对应的窗体代码文件中才行,放模块里就不行了??
------解决思路----------------------
你可以传入一个窗体对象作为参数,调用它的Invoke方法。
------解决思路----------------------
您的错误在于调用委托,

请直接复制如下代码运行。


Module Module1

    Public Delegate Sub voiddelegate(ByRef Obj As Object, ByVal Str As String)
    Private aTimer As System.Timers.Timer
    Dim i As Integer
    Dim j As Integer

    Private Label1 As Label
    Public Property _Label1() As Label
        Get
            Return Label1
        End Get
        Set(ByVal value As Label)
            Label1 = value
        End Set
    End Property

    Public Sub MySub()
        aTimer = New System.Timers.Timer(10)
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
        aTimer.Enabled = True
    End Sub


    Private Sub OnTimedEvent()
        aTimer.Enabled = False
        i = (i + 1)
        If Label1.InvokeRequired Then
            Label1.BeginInvoke(New voiddelegate(AddressOf UpdateUI), Label1, i.ToString)
        Else
            Label1.Text = i
        End If

        aTimer.Enabled = True
    End Sub

    Public Sub UpdateUI(ByRef Obj As Object, ByVal Str As String)
        Obj.text = Str
    End Sub
End Module

------解决思路----------------------
这个也加上运行。


Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Module1._label1 = Me.Label1
        Module1.MySub()

    End Sub
End Class

  相关解决方案