Checking if a Form is loaded

I found information regarding this from internet and works fine.

Public Function IsFormOpen(ByVal sender As String) As Boolean
Return ((From f In My.Application.OpenForms.Cast(Of Form)() _
Where f.Name.Equals(sender) Select f.Name).ToList.Count > 0)
End Function

And I called like this

If IsFormOpen("Form1") Then
MsgBox("it's open!")
Else
MsgBox("it's not open!")
End If
 
If you're going to use LINQ then this would be more appropriate:
VB.NET:
Return My.Application.OpenForms.Cast(Of Form)().Any(Function(f) f.Name = sender)
I don't think that 'sender' is an appropriate name for that parameter mind you. Also, I'd consider it far better to use a type rather than a String to specify the form you're looking for:
VB.NET:
Public Function IsFormOpen(Of TForm As Form)() As Boolean
    Return My.Application.OpenForms.OfType(Of TForm)().Any()
End Function
Usage:
VB.NET:
If IsFormOpen(Of Form1)() Then
    MessageBox.Show("A Form1 instance is open.")
Else
    MessageBox.Show("There is no Form1 instance open.")
End If
Having said all that, I'm still interested to know the context because I doubt that that is really the best way to handle what you want to do.
 
Back
Top