How to ensure only a single instance of my application runs?

You create a named Mutex when you start the application. Check GetLastError to see if an other instance is already running.

Put this code right after “begin” in your DPR file. Replace the GUID with one of your own. When I need a text constant that’s unlikely to be used for anything else, I usually just hit Ctrl+G to get a GUID!

if CreateMutex(nil, True, '6EACD0BF-F3E0-44D9-91E7-47467B5A2B6A') = 0 then
  RaiseLastOSError;

if GetLastError = ERROR_ALREADY_EXISTS then
  Exit;

It might look like the code is leaking an handle because it’s not saving the return of CreateMutex. It’s not. Windows will automatically release the handle when our application is terminated, and that’s absolutely fine with us.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)