views:

363

answers:

2

I am developing a Windows Forms application. I have four forms which is inherited from Baseform in another project. In all four forms I am using a label to show some transaction count based on network status. I have implemented a thread which gets the active form of application and setting up the text. The code works fine if application screen is active. If I minimize and open any other application, I am getting an null error exception.

How do I get the active form of an application?

Private Sub StartThread() 
    pollThread =New Thread(AddressOf PollfileStatus) 
    pollThread.IsBackground =True
    running =True
    pollThread.Start()
End Sub

Private Sub PollfileStatus() 
    While (running)
        Try
            For Each e As Control In Me.ActiveForm.Controls 
                If (e.Name = "pbStatus") Then
                    e.Invoke(New SetTextCallback(AddressOf Settext), 
                        New Object() {e, 10}) 
                End If
            Next
        Catch ex As Exception 
            Throw New ApplicationException(ex.Message) 
        End Try
        Thread.Sleep(6000)
    End While
End Sub
A: 

You should look into the Application.OpenForms shared property. It contains a collection of all forms in your application.

EDIT: Since you're working with .net 1.1 and don't have access to Application.OpenForms, here are some suggestions:

  • Implement your own shared class (module) that contains an ArrayList of forms. You could then create a base class inheriting from Form, handle the Load event to add the current form to the list of forms and the Closed event to remove it. Once you have that class, have all your real forms derive from it. BTW, it's (almost) how it is done in .Net 2.0.
  • Turn the problem around and have the working thread raise events when the values change that you can handle in each form to update it.
Julien Poulin
Hi Julien Poulin ,But i am using .net 1.1 frame work where Application.OpenForms is not supported
+2  A: 

Understandably Me.ActiveForm is empty, since minimizing your form makes it inactive. You have two options:

  • Test if Me.ActiveForm is empty, and if so, do not update the label. This will effectively 'pause' label updates, until the user restores the window again.

  • Create a property on your class that contains your thread, to pass a reference of the form you have to update. This way the label on the given form will update even if it is not the active form. This might be a better option, it will update even if the form is inactive in the background, for example.

Wez