busarider29
busarider29

Reputation: 305

Close one form when the "Main" form's focus is true

I have two forms in my project (Form1.vb with screen called "MainPanel", and From2.vb with screen called "frmTestSelect"). I have a button on the MainPanel that opens frmTestSelect. frmTestSelect is a much smaller screen/form than MainPanel. When both forms are open, I want a user to be able to click on the MainPanel form, thus closing the frmTestSelect screen. As of right now, when I click on the MainPanel, all it does is bring MainPanel into focus but leaves the FrmTestSelect screen open in the background. I want to close it if MainPanel's focus or any of it's object's focus is true. What is the simplest way to do this? Thank you.

Upvotes: 0

Views: 419

Answers (2)

George Popov
George Popov

Reputation: 76

You can keep a reference to the live instance of frmTestSelect in MainPanel (in a member variable for example), and invoke .Close() on it if MainPanel gets focus.

If you make MainPanel an MDIParent, and frmTestSelect an MDIChild (by specifying .MDIParent = MainPanelInstance), you can access all MDIChildren of MainPanel any time you gain focus, and close said children.

That said, if you go the MDIParent route, the child form will never get "hidden" behind its parent.

Upvotes: 1

Joe Uhren
Joe Uhren

Reputation: 1372

Dim frmTestSelect As Form2 = Nothing

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    frmTestSelect = New Form2
    frmTestSelect.Show()
End Sub

Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
    If frmTestSelect IsNot Nothing Then
        frmTestSelect.Close()
    End If
End Sub

Update: Changed Form1 event to Activated so that it closes Form2 even if a control on Form1 was clicked.

Upvotes: 2

Related Questions