Thread: a great little code snippet...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Location
    pacific northwest
    Posts
    37

    Smile a great little code snippet...

    i've been wondering how i could allow only a single instance of an application... here it is.

    Code:
    /* szClassName = Window Class Name */
    
    if(CreateMutex(NULL, FALSE, szClassName) && (GetLastError() == ERROR_ALREADY_EXISTS)) {
            SetForegroundWindow(FindWindow(szClassName, NULL));
            return 0;
    }
    hope this is helpful to a few.

    oh... and that's placed in the your WinMain for those who don't know.

    cheers!
    Last edited by skeptik; 09-15-2002 at 09:40 PM.
    "No, I am not wise, but I am a lover of wisdom." --Pythagoras

  2. #2
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    Or my favorite (again at teh begining of WinMain)

    Code:
    hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,PAGE_READONLY, 0, 32, szAppName);
    
    if (hMapping)// Check to see if app is already running
    {
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
    	sprintf(sBuffer,"%s is already running. Create another instance?",szAppName);
    	if(MessageBox(NULL, sBuffer,"Error",MB_ICONERROR| MB_YESNO)==IDNO)
               {
                    CloseHandle(hMapping);
    		ExitProcess(1);
               } 
        }
    } 
    else
    {
       MessageBox(NULL, "Error creating file mapping.", "Error",MB_ICONERROR| MB_OK);
       ExitProcess(1);
    }
    and CloseHandle(hMapping); on exit
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Explain this C code in english
    By soadlink in forum C Programming
    Replies: 16
    Last Post: 08-31-2006, 12:48 AM
  2. C code snippet which I need help understanding
    By c_me in forum C Programming
    Replies: 3
    Last Post: 07-28-2006, 06:06 AM
  3. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  4. snippet of for loop code problem
    By rayrayj52 in forum C++ Programming
    Replies: 8
    Last Post: 10-19-2004, 02:36 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM