PrevInstance

Requires: GfaWinx.lg32

Purpose

Checks if there is a previously running instance of the application and then sends a WM_ACTIVATEINST message.

Syntax

Bool = PrevInstance( [wParam][,lParam])

wParam, lParam: integer expression

Description

To prevent running multiple instances of the application use PrevInstance to send the WM_ACTIVATEINST message to all running applications. The application must process the WM_ACTIVATEINST message in the form’s _MessageProc event sub. A likely response would be to bring the form to the top using the OnTop property of the form object.

If PrevInstance returns True if a previous instance of the application is already running and the newly started instance can be ended using the End command.

Optionally the wParam and lParam parameters of the WM_ACTIVATEINST message can be used to submit further information to the already running instance. By default, the wParam of the WM_ACTIVATEINST message contains a hash value, obtained with Crc32(), of the application name (App.Name). This helps in checking if the WM_ACTIVATEINST is targeted for the current application.

Example

To try the example, run two instances of the IDE with this sample. The first instance creates a hidden and minimized form. The second instance sends the WM_ATIVATEINST message that is handled in frm1_MessageProc(). The hidden form is made visible, enabled, restored, and brought to the top.

$Library "UpdateRT"

UpdateRuntime      ' Patches GfaWin23.Ocx

$Library "gfawinx"

If PrevInstance() Then End

OpenW Hidden 1, 0, 0, 300, 200

Ocx Label lbl1 = "This application can only be started once", 0, 0, _X , _Y

Win_1.Minimize

Do

Sleep

Until Me Is Nothing

 

Sub Win_1_MessageProc(hWnd%, Mess%, wParam%, lParam%, retval%, ValidRet?)

' Example of processing WM_ACTIVATEINST:

If Mess% == WM_ACTIVATEINST && wParam% == Crc32(App.Name)

If Me.Visible = False Then Me.Visible = True

If Me.Enabled = False Then Me.Enable

Me.Restore

Me.ToTop

EndIf

End Sub

Remarks

The PrevInstance function uses a mutex to detect if there is an already running instance. If not, the handle of the mutex is stored in an AutoFreePtr object, which makes sure the handle of the mutex is closed properly using the CloseHandle() API on application exit, even in the case of a runtime error, Stop or End commands.

See Also

_Instance, AutoFreePtr

{Created by Sjouke Hamstra; Last updated: 22/12/2021 by James Gaite}