views:

663

answers:

5

I tried the following code but it does not retrieve text from foreground window!

procedure TForm1.Button1Click(Sender: TObject);
 var
  title : pansichar;
  s : string;
begin
    GetWindowText(GetForegroundWindow(), title,GetWindowTextLength(GetForegroundWindow()) + 1);
    s := title;
    showmessage(s);
end;
+3  A: 

Replace this line:

  title : pansichar;

with this:

  title: array[0..255] of Char;
Bruce McGee
+2  A: 

Try this code

procedure TForm1.Button1Click(Sender: TObject);
 var
  title : array[0..254] of Char;
  s : string;
begin
    GetWindowText(GetForegroundWindow(), title,255);
    s := title;
    showmessage(s);
end;

Bye.

RRUZ
now i am getting this error:[Error] Unit1.pas(31): Incompatible types: 'Array' and 'PAnsiChar'
Omair Iqbal
btw i am using delphi 7 maybe widechars are not supported
Omair Iqbal
yes removing ''wide'' made it work but why didnt widechar work?
Omair Iqbal
ok, i think you have delphi 2009 o 2010.
RRUZ
no i have delphi 7 personal edition
Omair Iqbal
If you're going to tell the function that there are `GetWindowTextLength + 1` characters in the array, then you should **use dynamic allocation** to ensure that there really are that many characters in the array, instead of using an array with 255 elements, which is completely arbitrary.
Rob Kennedy
Rob Thanks for the advice, I revised the code. to avoid problems with GetWindowTextLength . ;)
RRUZ
+5  A: 

Use this one:

var
  hwndForeground: HWND;
  titleLength: Integer;
  title: string;
begin
  hwndForeground := GetForegroundWindow();
  titleLength := GetWindowTextLength(hwndForeground);
  SetLength(title, titleLength);
  GetWindowText(hwndForeground, PChar(title), titleLength + 1);
  title := PChar(title);

  ShowMessage(title);
end;
actual
I've edited this to make it work for Unicode versions of Delphi as well.
Rob Kennedy
A: 

Can it be, that you have this issue?

Alexander
+1  A: 
procedure TForm1.Button1Click(Sender: TObject);
var
  liHwnd, liLength : Integer;
  lpChar : PChar;
begin
  liHwnd := GetForegroundWindow();
  liLength := GetWindowTextLength(liHwnd) + 1;
  lpChar := StrAlloc(liLength);
  Try
    GetWindowText(liHwnd, lpChar, liLength);

    showmessage(lpChar);
  Finally
    StrDispose(lpChar);
  End;
end;
Pmax