.net编程时在线程里使用Form上的控件的问题
Imports System.Threading
Public Class Form1
Delegate Sub AddListItem(ByVal IPString As String, ByVal ScanPort As Integer)
Public myDelegate As AddListItem
Public OpenPortCount As Integer = 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myDelegate = New AddListItem(AddressOf AddListItemMethod)
End Sub
Private Sub Start_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Start_Button.Click
Dim mythread As Thread
mythread = New Thread(New ThreadStart(AddressOf ThreadFunction))
mythread.Start()
End Sub
Private Sub ThreadFunction()
Dim mythread As Thread
mythread = New Thread(New ThreadStart(AddressOf DoScanThread))
mythread.Start()
End Sub 'ThreadFunction
Private Sub DoScanThread()
Dim myThreadClassObject As New ScanThreadClass(Me)
myThreadClassObject.run()
End Sub
Public Sub AddListItemMethod(ByVal IPString As String, ByVal scanport As Integer)
ListView_Result.Items.Add(IPString, OpenPortCount) 'ScanIP.ToString(), 0)
ListView_Result.Items(OpenPortCount).SubItems.Add(scanport.ToString())
OpenPortCount += 1
End Sub 'AddListItemMethod
End Class
Public Class ScanThreadClass
Private myFormControl1 As Form1
Public Sub New(ByVal myForm As Form1)
myFormControl1 = myForm
End Sub 'New
Public Sub run()
myFormControl1.Invoke(myFormControl1.myDelegate, New Object() {"11", 123})
End Sub
End Class
主要注意的就是Invoke的调用和Delegate的定义。