How to: Run Code When the Application Starts or Ends

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

The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help, depending on your active settings or edition. This Help page was written with General Development Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. 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