CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Threaded View

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    MFC Application: How can I limit my application to one instance?

    Q: How can I limit my application to one instance?

    A: You need to create a named mutex semaphore when you start your application. When the second one starts it tries to get access to the mutex but will fail...

    Code:
    // app.h
    class CYourApp : public CWinApp
    {
      ...
    
    private:
      HANDLE hMutex;
    };
    
    // app.cpp
    BOOL CYourApp::InitInstance()
    {
      // Create mutex
      hMutex = ::CreateMutex(NULL, TRUE, "GlobalMutex");
    
      switch(::GetLastError())
      {
        case ERROR_SUCCESS:
          // Mutex created successfully. There is no instance running
          break;
    
        case ERROR_ALREADY_EXISTS:
          // Mutex already exists so there is a running instance of our app.
          return FALSE;
    
        default:
          // Failed to create mutex by unknown reason
          return FALSE;
      }
    }

    Last edited by Andreas Masur; July 24th, 2005 at 04:46 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured