2895:How to check for app already running.

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

DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.


Return to Complete TI List