NO

Author Topic: Single instance console app?  (Read 3410 times)

andre104

  • Guest
Single instance console app?
« on: March 13, 2011, 04:29:47 PM »
How to make a single instance console app?
I found this, unfortunately it uses FindWindow(), which is not appropriate for console apps, right?

Offline Stefan Pendl

  • Global Moderator
  • Member
  • *****
  • Posts: 582
    • Homepage
Re: Single instance console app?
« Reply #1 on: March 13, 2011, 05:16:16 PM »
Register a Mutex.

You will find information at MSDN and by searching the web.
---
Stefan

Proud member of the UltraDefrag Development Team

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Single instance console app?
« Reply #2 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;
}

« Last Edit: April 04, 2011, 06:05:03 PM by timovjl »
May the source be with you

CommonTater

  • Guest
Re: Single instance console app?
« Reply #3 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;