Hi,

How can I make it so that my program will know that it is already running, and immediately exit if so (like someone clicks on my program ten times, only one process runs, the others exit)?

I apologize if this is a lame question but I couldn't find anything in the tutorials or by searching google or these excellent forums. Please, any ideas of how to do this would be greatly appreciated!

thanks in advance,
jpq
Posted on 2003-05-28 07:42:36 by johnqpublic2323
Posted on 2003-05-28 07:51:04 by Delight
Posted on 2003-05-28 07:52:38 by roticv
wow thanks guys! :) That thread hit the stop perfectly :)
Posted on 2003-05-28 08:57:05 by johnqpublic2323
Hi,

Just in case someone else is looking for this solution, and let's say this wonderful site is gone but this page is in google cache of something... anyway here is what I did:

I wanted my program to "do nothing" if clicked too many times.. no notice or anything, because it's already in memory doing it's job, why bother the user.

I used mutex. I added one line to the ".data" section:



szMutexAppName db "my_program_name_mutex", 0


and then added these lines to the start of my ".code" section, right after ".code" and "Start:"



; create mutex so we can detect if we're already running!
invoke CreateMutex, 0, 1, addr szMutexAppName
push eax
invoke GetLastError
.if eax == ERROR_ALREADY_EXISTS
pop eax
invoke CloseHandle, eax
jmp quit
.endif


For me, "quit" is at the end of my program, as this:



quit:
invoke ExitProcess,NULL


I believe this idea was written by the user "bazik" on this forum.

Anyway this works perfectly for me.

Many thanks for your help and for being a part of this excellent forum! I am so glad I found this place!

kindest regards,
jqp
Posted on 2003-05-28 16:39:01 by johnqpublic2323

MSDN:
If you need to detect whether another instance already exists, create a uniquely named mutex using the CreateMutex function. CreateMutex will succeed even if the mutex already exists, but the GetLastError function will return ERROR_ALREADY_EXISTS. This indicates that another instance of your application exists, because it created the mutex first.
Posted on 2003-05-29 01:36:55 by iblis
It is a *long* time since bazik did windows programming. Am I correct, bazik? :grin:
Posted on 2003-05-29 01:46:55 by roticv