How-To... - Exiting Windows From Your VB Program

The Windows API is a very powerful set of Function, Messages, Data Structures, Data Types, and Statements, which let you access the power of Microsoft Windows. The API saves you time by letting you use things Windows use, like in this example, Exit Windows. As you will see in this Tip, there is nothing to it. All you need to do is call a Function with some parameters and your program has the power to exit windows. Well, on with the Tip.

Start a new project. First, you need to insert a Standard Module. Next, type(or copy) the following function into the General Declarations section of the Standard Module :-

Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long

This Function is what you will call later on to Exit Windows by passing some parameters to it. To do this, you need some Constants. Add the following constants to the General Declarations of the Standard Module :-

Const SHUTDOWN_WIN = 1
Const REBOOT_WIN = 2

Now, we will create two Functions to either Shutdown or Restart Windows, depending on the users choice. Add the following functions to the Module :-

Function RebootWin() As Boolean
RestartWindows = CBool(ExitWindowsEx(REBOOT_WIN, 2))
End Function

Function ShutDownWin() As Boolean
ShutDownPC = CBool(ExitWindowsEx(SHUTDOWN_WIN, 1))
End Function

DodgeSoft Example - Exit WindowsNow, onto the Form. Add two buttons to the Form. The buttons in this example are called cmdShutDown and cmdRestart. The form in this example is designed(attractively :-)) like opposite.

Double click cmdShutDown and add the following code to the Click procedure :-

ShutDownWin

Double click cmdRestart and add the following code to the Click procedure :-

RebootWin

Those lines run the Function in the Module and returns either a True or False value. True means that Windows will either Restart or Shutdown. False means that a program has refused to close, usually because unsaved work is open.

Now, run the program. Click on either button and it will either ShutDown or Restart Windows. Makes sure all work is saved before running it.

You can download this example by clicking here


This site is Copyright © 1999 of David Cowan. VB How-To, Dodgesoft and DodgeSoft Productions is Copyright © 1999 of David Cowan. Source-code and programs are copyright of their respective owners. For a messageboard, click here