How to Determine Multiple Instances of a VB Application

ID Number: Q75641

1.00

WINDOWS

Summary:

Using Windows version 3.0 API function calls, you can determine if

another instance of your application is running. Using the same API

calls, you can also determine how many instances of an application are

running.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

You can use two Windows API function calls to determine how many

instances of your application are running. This can be useful if you

want to limit how many copies of your application can run at once.

The Windows KERNEL DLL (dynamic-link library) defines two functions

called GetModuleHandle and GetModuleUsage. GetModuleUsage uses the

handle returned from GetModuleHandle to determine how many instances

of your application are running. Below is a definition of each

function:

GetModuleHandle%(lpProgramName$)

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

This function retrieves the program handle of the specified program.

lpProgramName$ Points to a null-terminated character string that

specifies the program.

Return Value The return value identifies the program if the

function is successful. Otherwise, the return value is

zero.

GetModuleUsage%(hProgram%)

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

This function returns the reference count of a specified program.

hProgram% Identifies the program or an instance of the program.

This value can be determined with a call to

GetModuleHandle.

Return Value The return value specifies the reference count of

the program.

Example

-------

The following application is an example of how to limit an application

to a single instance:

1. Create a form called Form1.

2. Within the global-declaration section of the form, declare the

following Windows API functions:

Declare Function GetModuleHandle% Lib "Kernel" (ByVal lpProgramName$)

Declare Function GetModuleUsage% Lib "Kernel" (ByVal hProgram%)

3. Within the Form_Load event add the following code:

Sub Form_Load ()

hw% = GetModuleHandle("project.EXE")

If GetModuleUsage(hw%) > 1 Then

MsgBox "This program is already loaded!", 16

End

End If

End Sub

4. Compile the program as PROJECT.EXE

5. Run PROJECT.EXE from the Program Manager.

6. Run a second instance of PROJECT.EXE. It should display a message

box and terminate.

Reference:

"Programming Windows: the Microsoft Guide to Writing Applications for

Windows 3," by Charles Petzold (published by Microsoft Press, 1990)

"Microsoft Windows 3.0 Software Development Kit: Reference Volume 1"

WINSDK.HLP file shipped with Microsoft Windows 3.0 Software

Development Kit

Additional reference words: 1.00 3.00