Detect multiple run
BlitzPlus Forums/BlitzPlus Programming/Detect multiple run
| ||
Is there a way to detect if my program is already running ? I don't want to create a file on the hard disk or anything like that (someone already told me to try that but it's not working everytime as expected). MagicalTux |
| ||
Found that : http://www.blitzbasic.com/Community/posts.php?topic=21457 but it *must* be another way ... checking running processes etc... |
| ||
I know it can be done through the Windows API, but I don't remember which ones. |
| ||
You could do a 'FindWindow' on you own title bar. So you run, change your own app title to 'I am a Wombat' or something. Then do a FindWindow for 'WhizzyGame'. If you find it, then you are already running and will exit. Otherwise, set your apptitle to 'WhizzyGame' and continue. I think this is the FindWindowAPI call... .lib "user32.dll" FindWindow%( class$,Text$ ):"FindWindowA" |
| ||
Another way is to create a mutex each time you start your application. If the mutex is already opened, the application is already running. I tried this: .lib "kernel32.dll" CreateMutex%(lpMutexAttributes*,bInitialOwner,lpName$):"CreateMutexA" GetLastError%():"GetLastError" Const ERROR_ALREADY_EXISTS=183 mutex$="Choose_something" attributes=CreateBank(4) PokeInt attributes,0,0 mutex_h=CreateMutex(attributes,1,mutex$) FreeBank(attributes) If GetLastError() <> ERROR_ALREADY_EXISTS Print "1st time." Else Print "Already running." EndIf Input End It's a better way than FindWindow, but sadly it does not work. I always get an ERROR_INVALID_PARAMETER from GetLastError. I guess the problem is that the 2nd parameter must a BOOL (a byte) , is it possible to pass a byte to a DLL under Blitz ? |
| ||
Sending in a bank with the value of 0 is not the same as sending in NULL. Notice that in the userlib declaration, I changed the lpMutexAttributes paramter to be an int%, not a pointer*. .lib "Kernel32.dll" CreateMutex%(lpMutexAttributes%,bInitialOwner%,lpName$):"CreateMutexA" GetLastError%():"GetLastError" And the simple example code: Const ERROR_ALREADY_EXISTS=183 CreateMutex(0,1,"My Program Instance") ; Mutex accessible to any program If GetLastError() = ERROR_ALREADY_EXISTS Then Notify "My program is already running" ; Shutdown Else Notify "This is the only instance of My Program" ; OK EndIf Thanks for the idea, it works great. |
| ||
Ah, that was the problem. Thanks soja. |
| ||
Neat! |