C++ and STL
  Common Issues
  Destructor
  regex
  string
 MFC
  CButton
  CDialog
  CEdit
  CInternetSession
  CWinThread
  CWnd
 MS VS FAQ
  Compiling, building
  Debugging
  Editor
  Settings
 Win32, API
  Console
  File System
  Graphics
  Internet functions
  Kernel objects
  Security
  Sound
  Thread, process
  Window
 Windows NT/2K*
  Logon, logoff...
  Networking
  Service Packs
 | About
  About
  Links & Freeware

Powered by
CoderTown



How to ensure a single instance of the application at a time?

As the experience shows there is one proven method to do this: the creation of known kernel object. As a matter of fact when you use so called named kernel objects (like event, mutex, semaphore etc.) they are global over the system. You can easily check if there is another object with the same name. Of couse you'd better to invent unique name for this. Remember that all kernel objects share the same name space. See the classic sample for Win32 application:

int WINAPI WinMain(...) or MyApp()::InitInstance()
{

  HANDLE hAnyKernelObject = CreateMutex(NULL, FALSE,
                            "{E27D1C1E-B4D8-4439-83B4-0173E03C5D11}");
  // Use guidgen.exe to get your guid for this or just invent long specific name.
  if (GetLastError() == ERROR_ALREADY_EXISTS)
     return FALSE;
}

// Code for execution if no instance found.

MyApp()::ExitInstance()
{
  // ...
  CloseHandle(hAnyKernelObject);

  return 0;
}

Sample project is available.

The following link describes another aspects of the problem: Avoiding Multiple Instances of an Application by Joseph M. Newcomer.

Created: 2003-05-13
Updated: 2004-12-30

Google
 
Web visualcpp.net
msdn.microsoft.com codeguru.com