VB.NET how to check if a form already exists?

38 views Asked by At

for a chat client i want to create a new form instance for each user who is writing a private message and check if the user has an open instance already or not before creating an instance.

i tried to check it using dictionary but i could not get it to work..

Dim convs As New Dictionary(Of String, String)
Dim nf As New FrmDialog()


convs.Add(WritePUser, WritePMessage)
nf.Show()

If convs.ContainsKey(WritePUser) Then
    MsgBox("im already open")
Else
    nf.Show()
End If
1

There are 1 answers

2
jmcilhinney On BEST ANSWER

It's hard to know whether the code you posted is in one place in your app or multiple but it doesn't make sense to declare and create the Dictionary where you use it. If you do that then you'll be creating a new Dictionary every time so you'll never be able to see previously-created forms. You need to create one Dictionary and assign it to a field, i.e. a class-level variable. You then use that one and only Dictionary every time. The values in the Dictionary should also be forms, not Strings, so that you can access the existing form. You also need to either remove forms from the Dictionary when they close or else check whether the existing form is disposed. The latter is probably the simpler option.

Private dialoguesByUserName As New Dictionary(Of String, FrmDialog)

Then:

Dim dialogue As FrmDialog

If Not dialoguesByUserName.TryGetValue(userName, dialogue) OrElse
   dialogue.IsDisposed Then
    'Either there is no existing form or the existing form has been closed.
    dialogue = New FrmDialog
    dialoguesByUserName[userName] = dialogue
    dialogue.Show()
Else
    'Focus the existing form.
    dialogue.Activate()
End If