Jak pobrać tekst obecnie aktywnego okna

wesoledi

Na formatce umieść obiekt Timer o nazwie Timer1, oraz Edit o nazwie Edit1.
A oto kod:

function NT_InternalGetWindowText(Wnd: HWND): string; 
type 
 TInternalGetWindowText = function(Wnd: HWND; lpString: PWideChar; 
  nMaxCount: Integer): Integer;  
 stdcall; 
var 
 hUserDll: THandle; 
 InternalGetWindowText: TInternalGetWindowText; 
 lpString: array[0..MAX_PATH] of WideChar; 
 oemStr: PChar; 
begin 
 Result  := ''; 
 hUserDll := GetModuleHandle('user32.dll'); 
 if (hUserDll > 0) then 
 begin @InternalGetWindowText := GetProcAddress(hUserDll, 'InternalGetWindowText'); 
  if Assigned(InternalGetWindowText) then 
  begin 
   InternalGetWindowText(Wnd, lpString, SizeOf(lpString)); 
   Result := string(lpString); 
  end; 
 end; 
end; 

procedure TForm1.Timer1Timer(Sender: TObject); 
begin 
edit1.text:=NT_InternalGetWindowText(GetForegroundWindow); 
end; 

Jest to napisane głównie dla Windows NT, 2000, XP.

FAQ

2 komentarzy

Ja zrobiłem coś takiego i działa mi pod każdym win.

var
H : HWND;
S : string;
I : integer;
begin
H:=Windows.GetForegroundWindow;
I := SendMessage(H, WM_GETTEXTLENGTH, 0, 0);
I := I + 1;
setlength(S, I);
SendMessage(H, WM_GETTEXT,I,longint(@S[1]) );
Label1.Caption:='Nazwa okna: '+S;
end;

U mnie to nie działa, bo mam Windozę 98 (Najlepszy system ;-)), ale mam też Delphi 2.0 i wiem, że nie zawsze będzie działać Ostatnia linijka funkcji NT_InternalGetWindowText:

Result := string(lpString);

lepiej napisać:

Result := WideCharToString(lpString);