Pelles C forum

C language => Windows questions => Topic started by: andre104 on March 13, 2011, 04:29:47 PM

Title: Single instance console app?
Post 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?
Title: Re: Single instance console app?
Post by: Stefan Pendl on March 13, 2011, 05:16:16 PM
Register a Mutex.

You will find information at MSDN and by searching the web.
Title: Re: Single instance console app?
Post by: TimoVJL on March 13, 2011, 05:17:29 PM
Try this:
Code: [Select]
#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;
}

Title: Re: Single instance console app?
Post by: CommonTater on April 06, 2011, 08:31:22 AM
another very similar way of doing the first run mutex is this....
Code: [Select]
// Test if first copy.
CreateMutex(NULL,1,L"MY_NIFTY_MUTEX_NAME");
if (GetLastError() == ERROR_ALREADY_EXISTS)
  return 0;