我尝试在Form2中向Listbox添加项目,但是注意无法添加,当我将listbox放在同一个表单中时,哪个线程运行良好...有人可以帮助它使用Form2吗?这是代码:
Public Class Form1
Dim testthread As Threading.Thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Control.CheckForIllegalCrossThreadCalls = False
testthread = New Threading.Thread(AddressOf testira)
testthread.Start()
End Sub
Sub testira()
Form2.ListBox1.Items.Add(TextBox1.Text)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Form2.Show()
End Sub
End Class
答案 0 :(得分:0)
这是一个例子......
Public Class Form1
Private f2 As New Form2
Private Delegate Sub AddItemDelegate(ByVal item As String)
Private Delegate Function GetTextboxTextDelegate(ByVal TB As TextBox) As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testthread As New Threading.Thread(AddressOf testira)
testthread.Start()
End Sub
Sub testira()
Dim item As String = GetTextboxText(TextBox1)
AddItem(item)
End Sub
Private Function GetTextboxText(ByVal TB As TextBox) As String
If TB.InvokeRequired Then
Return TB.Invoke(New GetTextboxTextDelegate(AddressOf GetTextboxText), New Object() {TB})
Else
Return TB.Text
End If
End Function
Private Sub AddItem(ByVal item As String)
If Me.InvokeRequired Then
Me.Invoke(New AddItemDelegate(AddressOf AddItem), New Object() {item})
Else
If IsNothing(f2) OrElse f2.IsDisposed Then
f2 = New Form2
End If
f2.ListBox1.Items.Add(item)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If IsNothing(f2) OrElse f2.IsDisposed Then
f2 = New Form2
End If
f2.Show()
End Sub
End Class