Pelles C forum
C language => Windows questions => Topic started by: andre104 on March 13, 2011, 04:29:47 PM
-
How to make a single instance console app?
I found this (http://www.bcbjournal.org/articles/vol3/9911/Single-instance_applications.htm), unfortunately it uses FindWindow(), which is not appropriate for console apps, right?
-
Register a Mutex.
You will find information at MSDN and by searching the web.
-
Try this:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
TCHAR szMutex[] = "Global\\{6EBCEE90-C5EB-4891-A818-D7ED72F3AE3A}";
int main(int argc, char **argv)
{
// Try to open the mutex.
//HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, szMutex);
HANDLE hMutex = OpenMutex(SYNCHRONIZE, 0, szMutex);
if (hMutex) {
printf("Already running %Xh %d\n", (int)hMutex, GetLastError());
return 0;
}
hMutex = CreateMutex(0, 0, szMutex);
// ***************
printf("First run %Xh\npress enter to stop \n", (int)hMutex);
getchar();
// ***************
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return 0;
}
-
another very similar way of doing the first run mutex is this....
// Test if first copy.
CreateMutex(NULL,1,L"MY_NIFTY_MUTEX_NAME");
if (GetLastError() == ERROR_ALREADY_EXISTS)
return 0;