Mega Code Archive

 
Categories / Delphi / Examples
 

One application instance

Title: One application instance Question: It is possible to work with only one instance of your applications? Take a loock to this source code, and try it IT WORKS. Answer: var MH, Hwnd2 : THandle; implementation {$R *.DFM} function ReadAppHandle : Integer; begin Result := 0; with TRegistry.Create do begin RootKey := HKEY_LOCAL_MACHINE; if OpenKey('APP_INSTANCES\' + Application.Title, True) then Result := ReadInteger('HandleID'); CloseKey; end; end; procedure WriteAppHandle; begin with TRegistry.Create do begin RootKey := HKEY_LOCAL_MACHINE; if OpenKey('APP_INSTANCES\' + Application.Title, True) then WriteInteger('HandleID',Application.Handle); CloseKey; end; end; Initialization // Create the mutex MH := CreateMutex(nil, false, PChar(Application.Title)); if (MH NULL) and (GetLastError = ERROR_ALREADY_EXISTS) then begin //read handle from reg. Hwnd2 := ReadAppHandle; if (IsIconic(Hwnd2)) then begin ShowWindow(Hwnd2,SW_RESTORE); Halt; end else begin SetForeGroundWindow(Hwnd2); BringWindowToTop(Hwnd2); Halt; end; end else WriteAppHandle; end.