Главная страница | назад





Article #16769: Using a Mutex to check for previous instances

 Question and Answer Database

FAQ1769C.txt   Using a Mutex to check for previous instances
Category   :Windows API
Platform    :All
Product    :C++Builder  1.x

Question:
How do I check if there is a previous instance 
of my application running?

Answer:
Among the many ways that have been used to do this, using a 
mutex is probably the easiest.  The following code illistrates
how to use a Mutex to do this.

HANDLE CheckForPrevious (const char *MutexName){
    //try to create the mutex
    HANDLE Mutex = CreateMutex (NULL, true, MutexName);
    //check if we where allowed to create the mutex
    //if we where not allowed to do this then return 0
    //saying that there is a previous instance of the program
    int nResult = GetLastError ();
    if (!nResult)
        return 0;
    //if it was create return the Mutex Handle
    else
        return Mutex;
}

you can use this function at the start of an app to see if the 
app is already running like so:
...
Handle Mutex = CheckForPrevious (MutexName);
if (!Mutex){
    MessageBox (NULL, "Previous instance of the application running",
                "Previous Instance", MB_OK | MB_ICONEXCLAMATION);
    return 1;
}

...

7/2/98 10:32:32 AM
 

Last Modified: 01-SEP-99