Pergunta

i am creating a form by codes.

i am using this code

Dim frmNew As New Form2
    If frmNew.ShowInTaskbar = True Then
        frmNew.Close()
    End If
    Dim b As Button = DirectCast(sender, Button)
    frmNew.StartPosition = FormStartPosition.CenterScreen
    frmNew.Name = b.Name
    frmNew.Text = b.Text
    Try
        frmNew.Show()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

i have a design in my form2 so this is the form that im using in the declaration of frmnew after clicking the button it shows my new form but when i click again the button, it generates a new form the same in the first one. i want to close first the form before generating a new form.

i am using this code in my Multiple user LAN CHAT.

Thanks for the help.

Foi útil?

Solução

To find if another instance of the same form is currently open, you could search the collection Application.OpenForms and check if it contains a form with the same name of your Form2. Of course you should avoid to have two unrelated forms with the same name.

Dim k = Application.OpenForms.Cast(Of Form).Where(Function (x) x.Name = "yourFormName").SingleOrDefault() 

if k IsNot Nothing Then
   k.Close()
End If

Dim frmNew As Form2
frmNew = new Form2
Dim b As Button = DirectCast(sender, Button)
frmNew.StartPosition = FormStartPosition.CenterScreen
frmNew.Name = b.Name
frmNew.Text = b.Text

Try
    frmNew.Show()
Catch ex As Exception
    MsgBox(ex.Message)
End Try

This approach avoids a global variable to keep track of the previous instance.

After a quick check I think that the search code could be reduced to

Dim k = Application.OpenForms.Cast(Of Form2).SingleOrDefault() 

And this will avoid also a possible name conflict with an unrelated form with the same name

Outras dicas

I think this will work

Global declaration variable, inside class

Dim frmNew as New Form2

And inside your method:

If frmNew.ShowInTaskbar = True Then
    frmNew.Close()
End If
frmNew = New Form2
Dim b As Button = DirectCast(sender, Button)
frmNew.StartPosition = FormStartPosition.CenterScreen
frmNew.Name = b.Name
frmNew.Text = b.Text
Try
    frmNew.Show()
Catch ex As Exception
    MsgBox(ex.Message)
End Try

You should declare frmNew globally inside you class. This has the advantage that you don't have to worry about closing other forms at all.

So, declare it globally (outside of any method):

Dim frmNew as Form2

And inside your method:

If frmNew IsNot Nothing Then
    frmNew.Close()
frmNew = New Form2
Dim b As Button = DirectCast(sender, Button)
frmNew.StartPosition = FormStartPosition.CenterScreen
frmNew.Name = b.Name
frmNew.Text = b.Text
Try
    frmNew.Show()
Catch ex As Exception
    MsgBox(ex.Message)
End Try

Now each time the method is called, the same frmNew will be (re-)initialized, i.e. you're only working with a single Form2 at all times.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top