Restricting D applications to a single instance

Preetpal preetpal.sohal at gmail.com
Mon Feb 22 03:28:36 UTC 2021


On Monday, 22 February 2021 at 02:39:58 UTC, Steven Schveighoffer 
wrote:
> On 2/21/21 9:29 PM, Preetpal wrote:
>> I want to restrict a D application to a single instance. Is 
>> there a way to do this using the D standard library?
>
> When you say "application", you mean a class or type?
>

I decided to implement what I meant (single application 
(executable) instance restriction) using the Windows API (since 
my application only runs on Windows currently anyways):

     // Ensures only one instance of application can run at one 
time
     HANDLE globalMutexHandle = CreateMutex(NULL, true, 
"multi-monitor-window-maximization");
     if (globalMutexHandle == NULL) {
         return -1;
     }
     DWORD lastErrorAfterMutexCreationAttempt = GetLastError();
     if (lastErrorAfterMutexCreationAttempt == 
ERROR_ALREADY_EXISTS) {
         return -2;
     } if (lastErrorAfterMutexCreationAttempt == 
ERROR_INVALID_HANDLE) {
         return -3;
     }
     scope(exit) {
         ReleaseMutex(globalMutexHandle);
         CloseHandle(globalMutexHandle);
     }

This prevents someone from opening my particular application 
twice (so there cannot be two processes running of the same 
application/executable). I also updated by Github GIST code with 
the update.


More information about the Digitalmars-d-learn mailing list