1
votes

I have 2 forms: Form1 and Form2.
In Form1 I open Form2 in a new Thread by clicking on Button1.
I want to set the title of Form2 but I have no Idea how and whetever it is possible. Here is the code from Form1 , Form2 is just an empty Form:

Public Class Form1
    Dim TH As New Threading.Thread(AddressOf FormShow)

    Private Shared Sub FormShow()
        Dim FF As New Form2
        FF.Show()
        Do While FF.Visible
            Threading.Thread.Sleep(100)
            Application.DoEvents()
        Loop
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TH.Start()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        'How to change the Form2 title?
        'I need something like : TH.Form2.Text="NewTitle"?
    End Sub
End Class

If I start the code and click on Button1 Form2 will open. But how can I change the window title in Form2 when I press Button2 on Form1? Any ideas? Thanks.

1
Why do you need Form2 in a different Thread? What problem are you solving here? In general, accessing Forms across Threads causing more problems than its worth...Idle_Mind
My app has basically 2 Threads. Thread 1 = a form with "STOP" button. Thread 2 = CPU intensive calculations. So if I click in the form on "STOP" the whole app will quit. What I need here is to get or set some data between processes. If there is a better way I will do it.MilMike
The correct approach is to move the WORK (not the Form) onto a different thread. Do a search for BackgroundWorker() control and you'll get a billion examples.Idle_Mind
So you described the task you want to do. What is the problem you are trying to solve?Neolisk
i have no idea - the problem part is the task of the crazy professor I am working with. He will write his own calculation script in my software. My software will convert the code to exe and run it using the threads.MilMike

1 Answers

3
votes

From my comment above:

The correct approach is to move the WORK (not the Form) onto a different thread. Do a search for BackgroundWorker() control and you'll get a billion examples.

It is technically possible to do what you want in your original question, however:

Public Class Form1
Public Shared FF As New Form2

    Dim TH As New Threading.Thread(AddressOf FormShow)

    Private Sub FormShow()
        Application.Run(FF)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TH.Start()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If Not IsNothing(FF) AndAlso Not FF.IsDisposed Then
            FF.BeginInvoke(Sub(title)
                               FF.Text = title
                           End Sub, New Object() {"Hello"})
        End If
    End Sub

End Class

This is NOT the recoommended approach, though!