Search code examples
.netvb.netformsprogram-entry-pointlifecycle

Create a new instance of a form and keep it open


I have created two projects. One of the projects is the StartUp project. And the other is the GUI. I am trying to start the form in GUI though the StartUp project (referencing GUI).

StartUp Project:

Imports Container

Module modMain
    Sub main()
        Shell.Start()
    End Sub
End Module

GUI Project:

'----------------Form File------------------

Public Class Container

End Class

'----------------Shell File------------------

Public Class Shell
    Private Shared container_ As New Container

    Public Shared Sub Start()
        container_.Controls.Add(host_)
        container_.Show()
    End Sub

    Private Shared host_ As Panel

    Private Sub InitLayout()

        host_ = New System.Windows.Forms.Panel()
        Dim btn As New Button()
        btn.Text = "Click me"
        host_.Controls.Add(btn)

    End Sub

End Class

When I run it the form appears for only a few seconds then immediately closes. (I think) This is because I have not put any closing handlers but I am unsure how to do this.

The aim is to keep it open until the user closes it.


Solution

  • The reason the form is closing is because your application is closing which in turn closes all the open forms.

    Try specifying a form using Application.Run. Something like this:

    Module modMain
        Sub Main()
            Dim guiForm As Form = Shell.MainGuiForm
            Application.Run(guiForm)
        End Sub
    End Module
    

    You will need to have a reference to the form in your Shell class:

    Public Class Shell
        Private Shared _container As New ContainerForm
        Public Shared ReadOnly Property MainGuiForm As Form
            Get 
                Return _container
            End Get
    End Class