How to Set Focus to First VB .EXE Instance When Second Invoked

ID Number: Q84585

1.00

WINDOWS

Summary:

This article describes how to set the focus to the first instance of a

Visual Basic .EXE application when you attempt to invoke a second

instance of the same application. This feature prevents multiple

copies (instances) of the same program from running in memory.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

An example of this behavior is shown by the File Manager shipped with

Windows. If the File Manager is already running and you try to start a

second instance of it, the focus is simply shifted to the copy that is

already running so that another occurrence is not started. By using the

following function, you can achieve the same effect in a Visual Basic

application.

Steps to Reproduce Behavior

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

1. Run Visual Basic, or from the File menu, choose New Project (ALT,

F, N) if Visual Basic is already running. Form1 is created by

default.

2. Place a command button (Command1) on Form1. Set the Caption

property to END. In the Command1_Click event, put the keyword END

as the only line of code.

3. Put the following declarations in either the global module or the

general Declarations section of Form1. There are three

declarations, and each must be on one line.

Declare Function FindWindow% Lib "user" (ByVal lpClassName As Any,

ByVal lpCaption As Any)

Declare Function ShowWindow% Lib "User" (ByVal Handle As Integer,

ByVal Cmd As Integer)

Declare Function SFocus% Lib "User" Alias "SetFocus" (ByVal Handle As

Integer)

4. Put the following code in the Form1.Load event:

Title$ = "Test Program"

X% = CheckUnique(Title$)

If X% = 0 Then

End

End If

Form1.Caption= Title$

5. Create the following general function:

Function CheckUnique (FormName As String) As Integer

Dim Handle As Integer

Const NULL = 0&

Const WM_SYSCOMMAND = &H112

Const SC_CLOSE = &HF060

Handle = FindWindow(0&, FormName)

If Handle = 0 Then

' -1 is a true value

CheckUnique = -1

Else

X% = ShowWindow(Handle, 1)

X% = SFocus(Handle)

' 0 is a false value

CheckUnique = 0

End If

End Function

6. From the File menu, choose Make EXE File.

7. Press F5 to run the program.

If you try to launch a second occurrence of the program, it will

simply give focus to the first. If you try to launch a second

occurrence while the first occurrence is minimized, it will restore

the first occurrence and give it the focus. A second occurrence will

not be loaded into Windows.

Additional reference words: 1.00