Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Pascal
Expertise: Beginner
Apr 17, 1997

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. If it finds an instance of an app already running, it brings it to the foreground, then closes the currently executing instance. This is a useful function to have to make sure that you only have one instance of your program running at any time. I won't go into the particular details, but in case you've never seen this code or a variation of it, then all you do is save this code to a unit file called PREVINST.PAS, then put the PREVINST.PAS file in your uses statement, call GotoPreviousInstance in your FormCreate method (make sure it's the main form), and it'll check to see if you'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;



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.

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

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date