Date: 02-16-2022
Return to Index
created by gbSnippets
'The approach is for your application to create a mutex each time it runs. Before
'doing so, it checks to see if a mutex by than name already exists. If your program
'is already running, starting it again will detect the mutex. You can then decide whether
'to open an additional instance or not.
'Approaches which use the FindWindow API depend on the wording of the caption.
'In my apps, I often modify the caption (such as including the name of a file that
'has been opened), so the mutex is more reliable.
'Other approaches include creating a file when your app runs, then deleting it when
'the apps closes. Or, opening an existing file when the app runs. Trying to open it
'will result in an error if a previous instance is running.
'Primary Code (mutex approach):
Local UniqueName as AsciiZ * %Max_Path
UniqueName = "gbSnippets" '
If CreateMutex(ByVal %Null, 0, UniqueName) = 0 _
Or GetLastError = %ERROR_ALREADY_EXISTS Then Exit Function Else Function = 1
'Compilable Example: (Jose Includes)
'compile and run this example. then run the EXE again to show that the 1st instance
'was detected. This example asks the user if another instance of the application should be created.
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "WIN32API.INC"
Function PBMain()
If InstanceTest = 0 Then If MsgBox ("Previous instance detected! Open new instance?", %MB_okcancel + _
%MB_IconInformation, "Previous Instance Check") = %IDCancel Then Exit Function
Local hDlg as Dword
Dialog New Pixels, 0, "Mutex Test",300,300,200,200, %WS_OverlappedWindow To hDlg
Dialog Show Modal hDlg
End Function
Function InstanceTest() As Long
'returns 0 if instance exits or cannot create mutex. otherwise returns 1.
Local UniqueName as AsciiZ * %Max_Path
UniqueName = "gbSnippets" '
If CreateMutex(ByVal %Null, 0, UniqueName) = 0 _
Or GetLastError = %ERROR_ALREADY_EXISTS Then Exit Function Else Function = 1
End Function
'gbs_00036
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm