Skip to main content
gamedev.net
🔒 Locked

Process Detection (Win32)

Started by doctorsixstring Feb 17, 2003 at 11:56 AM 5 replies 250+ views
Original Post
doctorsixstring
doctorsixstring
How would I detect whether or not a given application is running? I looked at the OpenProcess() function, hoping that it would work. Unfortunately, OpenProcess() requires a specific process ID #, which I don''t know how to provide. The reason I am doing this is that I want only one instance of my application to run at any given time. Thus, I want to see if an instance of the program is running before I allow a new one to start. Thanks, Mike
CWizard
CWizard
I cannot recall exactly how, but there is standard technique to do just that, and I don''t think it involves checking if the a process is running. I think you register a mutex, or something similar. Look up mutex in the SDK and you should find some info about doing this.


doctorsixstring
doctorsixstring
Thanks, CWizard.

Here's how I did it, for anyone who's curious:

(I cut out most of the non-mutex related code):

    
int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpCmdLine, int nShowCmd )
{
HANDLE hMutex = CreateMutex(0, TRUE, "SingleInstance Enforcement Mutex";);
if(GetLastError() == ERROR_ALREADY_EXISTS)
return 0;


/* ... Initialize windows, run message pump, etc. ... */


ReleaseMutex(hMutex);

return msg.wParam;
}


-Mike

[edited by - doctorsixstring on February 17, 2003 1:34:30 PM]
niyaw
niyaw
you probably want to use CloseHandle instead of ReleaseMutex, as the latter doesn't destroy the mutex, merely releases current thread's lock on it.

[edited by - niyaw on February 17, 2003 2:38:40 PM]
Dean Harding
Dean Harding
You can also use FindWindow, passing in your windows caption string. That way, if you find the window you can set focus to it before exiting...

If I had my way, I''d have all of you shot!


codeka.com - Just click it.

daerid
daerid
quote:
Original post by niyaw
you probably want to use CloseHandle instead of ReleaseMutex, as the latter doesn''t destroy the mutex, merely releases current thread''s lock on it.



Actually, no you don''t. If he called CloseHandle(), then after the first program instance called CloseHandle(), then the second instance wouldn''t return ERROR_ALREADY_EXISTS, thus defeating the purpose of doing this in the first place.

The mutex needs to stay alive for the duration of the entire first instances lifetime.

daerid@gmail.com
niyaw
niyaw
it does, read the code again.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.