devxlogo

Previous instance of a running application via EnumWindows

Previous instance of a running application via EnumWindows

Question:
Previous instance of a running application via EnumWindows

Answer:
The code below will check for the previous instance of an application. Ifit finds an instance of an app already running, it brings it to theforeground, then closes the currently executing instance. This is a usefulfunction to have to make sure that you only have one instance of yourprogram running at any time. I won’t go into the particular details, butin case you’ve never seen this code or a variation of it, then all you dois save this code to a unit file called PREVINST.PAS, then put thePREVINST.PAS file in your uses statement, call GotoPreviousInstance in yourFormCreate method (make sure it’s the main form), and it’ll check to see ifyou’ve got another instance currently running. Here’s the code:

{====================================================================== PREVINST.PAS – Prevents a second instance of the program from running. Called from the program’s project file. ======================================================================}unit Previnst;interfaceuses  WinTypes, WinProcs, SysUtils;type  PHWND = ^HWND;  function EnumFunc(Wnd: HWND; TargetWindow: PHWND): Bool; export;  procedure GotoPreviousInstance;implementationfunction 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.

This code doesn’t work with Delphi 2.0 programs! Why? It hasto do with the various WinAPI calls made here. These calls are specific tothe Win16 kernel, which assumes a single resource and tasking area. WithWinNT and Win95, this isn’t the case (well, it’s still somewhat true inWin95). You’re dealing with multiple threads and processes in theseenvironments, so you can’t assume that you have access to the same memoryspaces.

See also  Small Business Strategies with Venmo
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist