How to Exit a FORM automatically?

Sougata Ghosh 161 Reputation points
2021-04-04T15:24:30.037+00:00

I created a VB project of the type Console App (.Net Framework). The objective of the below code is to make a FORM appear and then immediately disappear. However although the form is appearing correctly it is not closing by itself. Can anyone pls help pointing out my mistake? I tried to see how the control moves by setting up a break point and found that after executing the statement Application.Run(New Form1) (i.e. after launching the form) the control does not move to the next statement Application.Exit() by itself. Only when I manually close the FORM (by clicking on x icon) do I find the control moving to the Application.Exit() statement. But then I have already closed the form manually so does this statement at all do anything? If not, then how to modify the code to make the FORM automatically close after being visible.

Imports System.Windows.Forms

Public Class Form1
    Inherits Form    'System.Windows.Forms.Form

End Class
Module Module1
    Sub Main() 'launches the console window

        Application.Run(New Form1) 'Opens a new Form
        Application.Exit(0)   'Supposed to close the form that was opened but not closing
    End Sub  'closes the console window

End Module

Also, please note I am deliberately not creating a WPF application as I want to understand how the classes/commands under the System.Windows.Forms namespace work.

Regards,
Sougata Ghosh

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,568 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2021-04-04T15:39:38.867+00:00

    Try something like this:

    Dim f As New Form1
    AddHandler f.Shown, Sub()
                            Thread.Sleep (1111)
                            f.Close()
                        End Sub
    Application.Run(f)
    

    Sleep was added to show the form for short period; you can remove it.

    0 comments No comments

0 additional answers

Sort by: Most helpful