Very simple single instance test
Posted: Thu Jul 03, 2008 8:02 pm
I was looking for a short and sweet way to test if my application was already running.
After reading blueznl's inspired and clear explanation of mutex, i came up with the following which works real fine.
If you remove the macros, comments and messages, you'll see how ridiculously simple it really is:
Any similiraty to blueznl's and Berikco's code is intentional !
Their code pointed me in the right direction...
(Berikco code is here, down the middle of the page)
The drawback to the above is that the running instance of the application does not jump to the front, whereas Berikco's method ensured that happened.
Anybody know a good, simple way to force an application to the front ? (if i'm going to understand, it HAS to be simple!)
After reading blueznl's inspired and clear explanation of mutex, i came up with the following which works real fine.
If you remove the macros, comments and messages, you'll see how ridiculously simple it really is:
Code: Select all
Macro eol
Chr(13) + Chr(10)
EndMacro
Macro MsgBox(msg = "J'attends...", titre = "information")
MessageRequester(titre, msg, 0)
EndMacro
EnableExplicit
Define.L error, hMutex
Define.S msg, mutex_name
; we attempt to open a named mutex
mutex_name = "Single_Instance_Test"
hMutex = OpenMutex_(#MUTEX_ALL_ACCESS,0,@mutex_name)
If hMutex <> 0
msg = " We were able to open the mutex object: " + Str(hMutex)
msg + eol + " We therefore know that it exists, and our application too."
msg + eol + " So, we simply leave quietly..." + eol
MsgBox(msg, "Discovering our mutex "+Str(hMutex))
else
msg = " Opening the mutex failed."
msg + eol + " Therefore, neither it nor our appplication exist."
; we'll remedy that right now . First the mutex:
hMutex = CreateMutex_(0,0,@mutex_name)
; then the application :
If OpenWindow(0,100,150,450,200,"Testing mutex " + Str(hMutex), #PB_Window_SystemMenu)
msg + eol + " We create it ("+Str(hMutex)+") as we launch our application..." + eol
MsgBox(msg,"Creating mutex "+Str(hMutex))
Define.L event
Repeat
event=WaitWindowEvent()
Until event=#PB_Event_CloseWindow
EndIf
EndIf
If hMutex <> 0 ; which should be always
CloseHandle_(hMutex)
EndIf
End
Their code pointed me in the right direction...
(Berikco code is here, down the middle of the page)
The drawback to the above is that the running instance of the application does not jump to the front, whereas Berikco's method ensured that happened.
Anybody know a good, simple way to force an application to the front ? (if i'm going to understand, it HAS to be simple!)
