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.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular