VB.NET Processing Before WinForm Display


I woke up this morning to an interesting question.

“Using VB.net 2008, I want my project to be a Windows Forms application, but upon startup, I want to check a few files to see if they exist and if they don’t I do not want the startup form to load. I just want the program to quit. If you have to start this type of application with a form, how do you keep the form from displaying?”

If you program in csharp, you probably already know the answer to this question, or at least you should.  If you don’t, you will when we finish here.  So since I consider this a VB.NET-specific question, I’m going to answer it using VB.NET syntax.

When csharp runs a Windows Forms application, it writes out the following code in Program.cs (in VS 2008, earlier versions put this in the main form).

static void Main()
    Application.Run(new Form1());

In VB.NET there is no code that looks like this, because VB.NET writes the code for us behind the scenes.

So to do what you want to do, we need to take over control of the Windows Form application.

Since I’m assuming that you already have the Windows Form application created, the next thing you’ll want to do is to create a module.  You can name it what ever you want, but I’m going to name mine “Main” for purposes of this article.

In your module, create a function called “main” that has the code CSharp would have given us.

    Public Sub main()
        Application.Run(New Form1())
    End Sub

Now go to your project properties and go to the Application tab.


Find the check box that says, “Enable Application Framework” and un-check it.


Then change the startup object to “Sub Main".”

At this point, your application should run as it always has.  To put the checks in that you requested, write that code prior to all the Application… statements that we put in sub main and put an if/then/end if statement around the Application… statements.

    Public Sub main()
        Dim ChecksWereOk As Boolean = False
        ' your checks here
        If ChecksWereOk Then
            Application. _
            Application.Run(New Form1())
        End If
    End Sub

And that should do the trick for you.

Related Post

Comments are closed.