community.borland.com

Article #16015: How to check for app already running.

 Technical Information Database

TI1015D.txt   How to check for app already running.
Category   :Windows API
Platform    :All
Product    :Delphi  1.0

Description:
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.

Reference:


7/16/98 4:33:59 PM
 

Last Modified: 01-SEP-99