对于聊天客户端,我想为每个正在编写私人消息的用户创建一个新的表单实例,并在创建实例之前检查用户是否已经有一个打开的实例。
我尝试使用字典检查它,但我无法让它工作..
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
很难知道您发布的代码是位于应用程序中的一个位置还是多个位置,但在使用它的地方声明和创建
Dictionary
是没有意义的。如果您这样做,那么您每次都会创建一个新的 Dictionary
,因此您将永远无法看到以前创建的表单。您需要创建一个 Dictionary
并将其分配给一个字段,即类级变量。然后你每次都只使用这个 Dictionary
。 Dictionary
中的值也应该是表单,而不是 Strings
,以便您可以访问现有表单。您还需要在关闭时从 Dictionary
中删除表单,或者检查现有表单是否已处理。后者可能是更简单的选择。
Private dialoguesByUserName As New Dictionary(Of String, FrmDialog)
然后:
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