- - * - WhiteUnicorn - * - -




* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >


Frequently Asked Questions

Getting an handle to a window in another application.

Question:

How do I get the handle of another application's window and make that window the active window?

Answer:

Using the Windows API function FindWindow() is the simplest and
most straightforward method of locating a given window provided you
know the exact window caption or class name. If you know only part of
the window's caption (ie: 'Netscape - ' + 'Some Unknown URL', you need
to use the Windows EnumWindows() function to enumerate all the active
windows, then call the Windows API functions GetWindowsText() and
GetClassName to see if you find a match for the window that you are
searching for.

The following example returns the window handle of the first window
enumerated that contains a partial match of the window title and an
exact match of the window's ClassName (if given) and brings that
window to the foreground.

type
  PFindWindowStruct = ^TFindWindowStruct;
  TFindWindowStruct = record
    Caption : string;
    ClassName : string;
    WindowHandle : THandle;
  end;

function EnumWindowsProc(hWindow : hWnd;
                         lParam  : LongInt) : Bool
{$IFDEF Win32} stdcall; {$ELSE} ; export; {$ENDIF}
var
  lpBuffer : PChar;
  WindowCaptionFound : bool;
  ClassNameFound : bool;

begin
  GetMem(lpBuffer, 255);
  Result := True;
  WindowCaptionFound := False;
  ClassNameFound := False;

  try
    if GetWindowText(hWindow, lpBuffer, 255) > 0 then
      if Pos(PFindWindowStruct(lParam).Caption, StrPas(lpBuffer)) > 0
       then WindowCaptionFound := true;

    if PFindWindowStruct(lParam).ClassName = '' then
      ClassNameFound := True else
        if GetClassName(hWindow, lpBuffer, 255) > 0 then
          if Pos(PFindWindowStruct(lParam).ClassName, StrPas(lpBuffer))
           > 0 then ClassNameFound := True;

    if (WindowCaptionFound and ClassNameFound) then begin
      PFindWindowStruct(lParam).WindowHandle := hWindow;
      Result := False;
    end;

  finally
    FreeMem(lpBuffer, sizeof(lpBuffer^));
  end;
end;

function FindAWindow(Caption : string;
                     ClassName : string) : THandle;
var
  WindowInfo : TFindWindowStruct;

begin
  with WindowInfo do begin
    Caption := Caption;
    ClassName := ClassName;
    WindowHandle := 0;
    EnumWindows(@EnumWindowsProc, LongInt(@WindowInfo));
    FindAWindow := WindowHandle;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  TheWindowHandle : THandle;
begin
  TheWindowHandle := FindAWindow('Netscape - ', '');
  if TheWindowHandle = 0 then
    ShowMessage('Window Not Found!') else
    BringWindowToTop(TheWindowHandle);
end;



* #WhiteUnicorn/ StartPage/ Documentation/DelphiFAQ >



- - * - Anastasija aka WhiteUnicorn - * - - LJLiveJournal
PFPhotoFile