[英]How can I update a control on another thread?
This is my situation, I have one button on my form.这是我的情况,我的表单上有一个按钮。
When I click it, I want a new instance of MyNewClass to make a Picturebox appear on my form.当我单击它时,我想要一个 MyNewClass 的新实例以使 Picturebox 出现在我的表单上。
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fooThread As New Threading.Thread(Sub() Foo())
fooThread.Start()
End Sub
Private Sub Foo()
Dim myInstance = New MyNewClass()
End Sub
End Class
Public Class MyNewClass
Public Sub New()
Dim testControl = New PictureBox()
testControl.BackColor = Color.Green
Form1.Controls.Add(testControl)
End Sub
End Class
The problem is, when I click the button, nothing appears.问题是,当我单击按钮时,什么也没有出现。
I've tried using an Invoke method in order to add the initialized picturebox to Form1 controls:我尝试使用 Invoke 方法将初始化的图片框添加到 Form1 控件:
Form1.Invoke(Sub() Form1.Controls.Add(testControl))
but then when I click Button1, I get an exception:但是当我单击 Button1 时,出现异常:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
Thanks for helping感谢您的帮助
Problem is that YourNewClass doesn't know Form1 as you expected.问题是 YourNewClass 并不像您预期的那样知道 Form1。 You must introduce it in global variable.您必须在全局变量中引入它。 This Code will work:此代码将起作用:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyForm = Me
Dim fooThread As New Threading.Thread(Sub() Foo())
fooThread.Start()
End Sub
Private Sub Foo()
Dim myInstance = New MyNewClass()
End Sub
End Class
Public Class MyNewClass
Public Sub New()
Dim testControl = New PictureBox()
testControl.BackColor = Color.Green
MyForm.Invoke(Sub() MyForm.Controls.Add(testControl))
End Sub
End Class
Public Module Module1
Public MyForm As Form
End Module
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.