Raven Blue Raven Blue - 3 years ago 131
Vb.net Question

How to pass a Form as a function parameter?

I have a function and it looks like this:

Function SpawnForm(Form)
Dim Spawn As New Form With {.TopLevel = False, .AutoSize = False}
Try
Spawn.Dock = DockStyle.Fill
MainForm.SpawnPanel.Controls.Add(Spawn)
Spawn.Show()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return Nothing
End Function


I want to pass the parameter onto the rest of the function, so if I were to call it as this:

SpawnForm(SettingsForm)


It will then spawn the existing form in my project called SettingsForm.

I know that the problem is this:

Dim Spawn As New Form


What should I do differently to pass the parameter?

djv djv
Answer Source

You can make a generic function with some constraints. This allows you to keep the form creation inside the method (instead of passing an instance). Also return the instance from the function.

Private Function SpawnForm(Of T As {New, Form})() As T
    Dim spawn As New T() With {.TopLevel = False, .AutoSize = False}
    Try
        spawn.Dock = DockStyle.Fill
        MainForm.SpawnPanel.Controls.Add(spawn)
        spawn.Show()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    Return spawn
End Function

Usage:

Dim mySettingsForm = SpawnForm(Of SettingsForm)()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download