Sean Long
Sean Long

Reputation: 2301

BringToFront isn't bringing form to the front

I'm trying to set up a button that does the following:

  1. Checks to see if a form is open (and has lost focus). If so, it brings that form to the front.
  2. If not, it opens a new instance of the form.

However, I've tried a few different methods and it will always either create a new form (if I use frm_About.visible as the check) or simply not do anything (with the following code).

Private Sub counter_aboutClick(sender As Object, e As EventArgs) Handles counter_About.Click
    If Application.OpenForms().OfType(Of frm_About).Any Then
        frm_About.BringToFront()
    Else
        Dim oAbout As frm_About
        oAbout = New frm_About()
        oAbout.Show()
        oAbout = Nothing
    End If
End Sub

I've heard that there's a bug with BringToFront in certain scenarios, am I hitting that bug?

Upvotes: 2

Views: 9265

Answers (1)

J...
J...

Reputation: 31393

VB.Net does a terrible thing and creates a default instance of a form (which can be referred to by its class name). This creates endless confusion and headaches - I suggest you read up on default instances (google can find a lot to read about, surely)

In this case, you have a class called frm_About as well as a default instance of that form which is also called frm_About. If you've created a new form of type frm_About then the following code

If Application.OpenForms().OfType(Of frm_About).Any Then
    frm_About.BringToFront()

will search your open forms to look for a form of type frm_About and, if it finds one, will attempt to bring the default instance of frm_About to the front - note that the open form can be (an in your case is most likely) not the default instance but any instance created with New frm_About().

To find the actual instance of the form you would have to do something like :

For Each openForm In Application.OpenForms()
    If TypeOf (openForm) Is frm_About Then _
                                   CType(openForm, frm_About).BringToFront()
Next

Upvotes: 4

Related Questions