Terminating Windows from a Visual Basic Application

ID Number: Q76981

1.00

WINDOWS

Summary:

The Visual Basic SendKeys function cannot be used to close Program

Manager in order to terminate Windows. To correctly close Program

Manager, you must invoke the ExitWindows API function, as shown

further below.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

You may want to terminate the current Windows session by closing the

Program Manager from within a Visual Basic application. You may think

that you can activate the Program Manager control menu and send the

appropriate key sequences using the Visual Basic SendKeys function.

However, this method will not work because after the Close menu item

is chosen, a system modal dialog box is opened that prompts you to

save changes to Program Manager. A system modal dialog box locks out

ALL other programs until it is satisfied. Thus, the keystroke you send

via the SendKeys function will never arrive in the dialog box.

To correctly close Program Manager, you must use the ExitWindows API

function. You can declare this API function in the GLOBAL.BAS module.

For example:

1. Start a new project in Visual Basic.

2. Draw a command button on the form.

3. Add the following line to GLOBAL.BAS:

Declare Function ExitWindows Lib "user" (ByVal dwReserved&,

ByVal wReturnCode%) as integer

(Note: This declaration must all be on one line.)

4. Add the following line of code to the command button Click

procedure:

RetVal% = ExitWindows(0,0)

5. Run the program.

6. Click on the command button.

The ExitWindows API call initiates the standard Windows shutdown

procedure. If all applications agree to terminate, the windows session

is terminated and control returns to MS-DOS. If the ExitWindows API

call fails (due to an open MS-DOS session or some other reason), FALSE

is returned. You should check for this and handle it appropriately.

Steps to Reproduce Problem

--------------------------

1. Start a New Project in Visual Basic.

2. Draw a command button on the form.

3. In the command button Click event procedure, add the following

code:

AppActivate("Program Manager")

SendKeys "%{ }{DOWN 5}{ENTER 2}", 0 'ALT, SPACE, DOWN 5, ENTER 2

4. Run the program.

Note that the Program Manager does not close. Choosing the OK button

with the mouse will display a message stating "Can't quit at this

time." Choosing the Cancel button will display the message "Cannot

start more than one copy of the specified program." These messages are

misleading, but are the result of attempting an unsupported action.

Additional reference words: 1.00