View Full Version: Easy Way To check for mult instances

C++ Learning Community > C++ Tips > Easy Way To check for mult instances


Title: Easy Way To check for mult instances


inuyaga - November 26, 2003 01:31 PM (GMT)
Well this is an easy way to check for mult instances of a program running..
sence hPrevInstance is crap... you cant look for mult instances easlley, use
mutexes!!! :lol: yay... Dont worrey no multi threading involved :P.

so what you do is first thing on program entry call
CreateMutex(
NULL, //Ignored
TRUE,//The program is inital owner
"NAME");//The name of the mutex


then call
GetLastError() and if it = ERROR_ALREADY_EXISTS
you have another instance of your program running

//one thing the name pram of CreateMutex() must be the same for all instances
of the program if it isnt when windows goes to create the mutex and scanns its name list to see if a mutex with that name allready exists it will not find one. So the names must be tha same!!! and it must have a name
so here is the code

#include<winbase.h> //Multi threading cram CreateMutex
#include<windows.h>//If you dont know learn more c++

winmain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTRlpCmdLine,int nCmdShow){

HANDLE temp=CreateMutex(NULL,TRUE,"MULTI INST APP CHECK"); //Make the mutex
if(GetLastError() == ERROR_ALREADY_EXISTS) //check for it
MessageBox( NULL,"Hey there are more than one", "Multi inst", MB_OK |
MB_ICONINFORMATION ); //message if it exists
Sleep(100000); //sleep so we have time to start mult instance
CloseHandle(temp);//clean up your junk
return 0;
}

//I think this will compile and work

TheHawgMaster - November 26, 2003 09:39 PM (GMT)
I've always done it by registering a global ATOM but I guess that would work too...

Dragon - November 26, 2003 09:49 PM (GMT)
I've never needed to do that before, but it's nice to know.

Uraldor - November 27, 2003 12:28 AM (GMT)
That's a handy snippet of code if you just want to check for another instance, but if you want to do something like make the other instance the active window before you exit, then you'll need to use FindWindow() or somesuch.

OJ

ih8censorship - November 27, 2003 01:28 AM (GMT)
whats a mutex? whats a global ATOM?

Dragon - November 27, 2003 01:29 AM (GMT)
You can look up ATOM on the MSDN.

inuyaga - November 28, 2003 04:48 PM (GMT)
A Mutex is a dataaccess controler. basicalley a gate keeper for your data. Mainalley used in multi threading.


I HATE MULTITHREADING :angry:


MAKES MY HEAD POUND :wacko:


--rubs head--- ;)
--thinks to self -- need a advil <_<




* Hosted for free by InvisionFree