The Compiler
The Compiler

Reputation: 63

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.

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:

        Form1.Invoke(Sub() Form1.Controls.Add(testControl))

but then when I click Button1, I get an exception :
Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Thanks for helping

Upvotes: 0

Views: 64

Answers (1)

HYA
HYA

Reputation: 189

Problem is that YourNewClass doesn't know Form1 as you expected. 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

Upvotes: 2

Related Questions