Mega Code Archive

 
Categories / Delphi / Examples
 

Appopencheck

There are components available on the Delphi sites that provide this functionality for you if you want the easy way out. The most reliable method of ensuring only one instance of your application is running is to use a mutex (MUTual EXclusive). Take a look at the CreateMutex function in the Win32 API help file for more info. From memory, it goes something like this. var Mutex: THandle; begin Application.Title := 'MyApplicationName'; { Check for another application instance. } Mutex := CreateMutex(nil, False, PChar(Application.Title + 'Mutex')); if GetLastError = ERROR_ALREADY_EXISTS then Exit; Application.CreateForm(TForm1, Form1); Application.Run; end; ************************************************** and (separate code to create a mutex)... ***************** START PROJECT FILE EXAMPLE **************** program Project1; uses Forms, Windows, // necessary for the THandle and CreateMutex Unit1 in 'Unit1.pas' {Form1}; {$R *.RES} var AppMutex : THandle; begin AppMutex := CreateMutex(nil, true, 'MY_APP_MUTEX_NAME'); if GetLastError <> ERROR_ALREADY_EXISTS then begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end; end. ***************** END PROJECT FILE EXAMPLE ****************