How to: Run Code When the Application Starts or Ends (Visual Basic)

You use the events provided by the Visual Basic Application model to run code when the application starts or ends. The Project Designer provides access to the application's event-handler code.

Note

The Visual Basic Application model is available only for Windows Forms applications. For more information, see Overview of the Visual Basic Application Model.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To access the application's event-handler code

  1. Have a project selected in Solution Explorer. From the Project menu, click Properties.

  2. Click the Application tab.

  3. Click the View Application Events button to open the Code Editor.

    This opens the ApplicationEvents.vb file.

To run code when the application starts

  1. Have the ApplicationEvents.vb file open in the Code Editor. From the General menu, choose MyApplication Events.

  2. From the Declarations menu, choose Startup.

    The application raises the Startup event before the main application runs.

  3. If your application is a single-instance application, you may want to handle subsequent starts of the application. To do this, from the General menu, choose MyApplication Events.

  4. From the Declarations menu, choose StartupNextInstance.

    A single-instance application raises the StartupNextInstance event in the first instance of the application when a subsequent instance of the application starts. The subsequent instance then closes without raising any of its own events.

To run code when the application ends

  1. Have the ApplicationEvents.vb file open in the Code Editor. From the General menu, choose MyApplication Events.

  2. From the Declarations menu, choose Shutdown.

    The application raises the Shutdown event after the main application runs, but before it shuts down.

  3. From the General menu, choose MyApplication Events.

  4. From the Declarations menu, choose UnhandledException.

    The application raises the UnhandledException event if it encounters an unhandled exception. Because the application does not raise the Shutdown event after the UnhandledException event, you may want the UnhandledException handler to call the same shut-down code that the Shutdown handler calls.

See Also

Tasks

How to: Handle Application Events (Visual Basic)

Concepts

Overview of the Visual Basic Application Model