Raven Blue
Raven Blue

Reputation: 13

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?

Upvotes: 0

Views: 92

Answers (1)

djv
djv

Reputation: 15774

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)()

Upvotes: 1

Related Questions