- - * - WhiteUnicorn - * - -




* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >


2895:How to check for app already running.

KEYWORDS: check for app already running AREA: WinAPI

Q:  How can I write my Delphi program to detect if there is
already another copy running and exit if so?

A:  Create a unit called PrevInst and add it to your uses clause.
Here's the code:

 unit PrevInst;

 interface

 uses
  WinTypes, WinProcs, SysUtils;

 type
  PHWND = ^HWND;
  function EnumFunc(Wnd:HWND; TargetWindow:PHWND): bool; export;
  procedure GotoPreviousInstance;

 implementation

  function EnumFunc(Wnd:HWND; TargetWindow:PHWND): bool;
  var
    ClassName : array[0..30] of char;
  begin
    Result := true;
    if GetWindowWord(Wnd,GWW_HINSTANCE) = hPrevInst then
    begin
      GetClassName(Wnd,ClassName,30);
      if StrIComp(ClassName,'TApplication') = 0 then
      begin
        TargetWindow^ := Wnd;
        Result := false;
      end;
    end;
  end;

  procedure GotoPreviousInstance;
  var
    PrevInstWnd : HWND;
  begin
    PrevInstWnd := 0;
    EnumWindows(@EnumFunc,longint(@PrevInstWnd));
    if PrevInstWnd <> 0 then
      if IsIconic(PrevInstWnd) then
        ShowWindow(PrevInstWnd, SW_RESTORE)
      else
        BringWindowToTop(PrevInstWnd);
  end;

  end.

And then make the main block of your *.DPR file look
something like this--

begin
  if hPrevInst <> 0 then
    GotoPreviousInstance
  else
  begin
    Application.CreateForm(MyForm, MyForm);
    Application.Run;
  end;
end.

        TI



* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >



- - * - Anastasija aka WhiteUnicorn - * - - LJLiveJournal
PFPhotoFile