Results 1 to 4 of 4

Thread: allowing only 1 instance of app

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Posts
    1,091
    Hi,

    I want to prevent the user from starting more than 1 instance of my app.

    I would assume that I would put some code in the WinMain function to detect if a instance allready exists and then exit but not sure how I would implement it.

    I'm using VC++ W/OUT MFC.

    Any help would be appreciated..

    Dan

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Try this:
    Code:
    #include <windows.h>
    
    int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    	HANDLE hMutex = CreateMutex(NULL, TRUE, "Test Windows Program - only 1 instance");
    
    	if(GetLastError() == ERROR_ALREADY_EXISTS) {
    		MessageBox(NULL, "Already an instance", "Error", MB_OK);
    		return -1;
    	}
    
    	MessageBox(NULL, "This is first instance", "Okay", MB_OK);
    
    	ReleaseMutex(hMutex);
    	CloseHandle(hMutex);
    	return 0;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    Guest
    what is createmutex?

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    It creates a mutually exclusive handle. IE: only one can exist at the same time. So, what it does is it tries to create one. If one exists with that name then the handle to the existing one is returned, and GetLastError() returns ERROR_ALREADY_EXISTS.

    When the app has finished, it closes its handle onto the mutex. If all the mutex's threads have ended, the mutex is released from the system.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

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