Saaru Lindestøkke
Saaru Lindestøkke

Reputation: 2564

Reading Checkbox status from other thread

Basically it's this question but then for VB.net. I need to check the CheckBox state from another thread than the main thread. Solutions for the linked question contain C# code. On-line translators do not yield understandable results.

My code (stripped down to the essential parts):

Public Class UI
    'UI contains CheckBox1.
End Class

Public Class Worker
    Public Sub Input()
        Dim thrMyThread As New System.Threading.Thread(AddressOf Run)
        thrMyThread.Start()
    End Sub

    Public Sub Run()
        If UI.CheckBox1.Checked = True
            MsgBox("True")
            ShellandWait("application.exe")
        Else
            MsgBox("False")
            ShellandWait("application.exe")
        End If
    End Sub

End Class

ShellandWait is a custom function which starts a process and waits until it exits. Because of the ShellandWait I need another thread to keep my UI responsive.

UPDATE
I did find a work around by defining a Public boolean variable at the beginning of the Worker Class, which represents the state of the UI.CheckBox. So:

Public Class Worker
    Public cB As Boolean = UI.CheckBox.Checked
    ... 'Rest of Code
    Public Sub Run()
        If cB = True
            MsgBox("True")
            ShellandWait("application.exe")
        Else
            MsgBox("False")
            ShellandWait("application.exe")
        End If
    End Sub
End Class

Upvotes: 0

Views: 2507

Answers (1)

Max
Max

Reputation: 7596

This should work. This code will enable you to access the GUI from worker-threads.

Public Delegate Function GetCheckBoxChekedDelegate(cb As CheckBox) As Boolean

Public Function GetCheckBoxChekedFunction(cb As CheckBox) As Boolean
    Return cb.Checked
End Function

Public Function GetChecked(cb As CheckBox) As Boolean
    If cb.InvokeRequired Then

        Dim del As GetCheckBoxChekedDelegate
        del = AddressOf GetCheckBoxChekedFunction


        Dim parArray() As Object = {cb}

        Return CBool(cb.Invoke(del, parArray))
        'Return CBool(cb.Invoke(del, New Object() {cb}))
        'Return CBool(cb.Invoke(del, {cb}))

    Else
        Return cb.Checked

    End If
End Function

You can use the GetChecked function to get the checked state of the checkbox, the function will works both on the main thread, and on a worker thread.

When the GetChecked function is called from a worker thread the InvokeRequired will return true, so the cb.Checked value is read in the function GetCheckBoxChekedFunction which is called on the main thread by the cb.Invoke(del, {cb}) command.

Upvotes: 1

Related Questions