Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Allow only one instance of your application

Title: Allow only one instance of your application Question: How to prevent a second launch of your application ? Answer: var AtomText: array[0..31] of Char; procedure LookForPreviousInstance; var PreviousInstanceWindow : hWnd; AppName : array[0..30] of char; FoundAtom : TAtom; begin // put the app name into AtomText StrFmt(AtomText, 'OnlyOne%s', [Copy(Application.Title,1,20)]); // check to see if there's a global atom based on the app name FoundAtom := GlobalFindAtom(AtomText); if FoundAtom 0 then // another instance exists begin StrFmt(AppName,'%s', [Application.Title]); // change current title so that FindWindow doesn't see it Application.ShowMainForm := false; Application.Title := 'destroy me'; // locate the previous instance of the app PreviousInstanceWindow := FindWindow(nil,AppName); // give focus to the previous instance of the app // stop the current instance of the application Application.Terminate; if PreviousInstanceWindow 0 then if IsIconic(PreviousInstanceWindow) then ShowWindow(PreviousInstanceWindow,SW_RESTORE) else SetForegroundWindow(PreviousInstanceWindow); end; // make the global atom so no other instances can occur FoundAtom := GlobalAddAtom(AtomText); end; constructor TForm.Create(AOwner: TComponent); begin inherited; LookForPreviousInstance; ... end; destructor TForm.Destroy; var FoundAtom : TAtom; ValueReturned : word; begin // must not forget to remove the global atom, so first check to see if // there's a global atom already FoundAtom := GlobalFindAtom(AtomText); if FoundAtom 0 then ValueReturned := GlobalDeleteAtom(FoundAtom); inherited Destroy; end;