Omair Iqbal
Omair Iqbal

Reputation: 1838

getwindowtext not retrieving text

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;

Upvotes: 3

Views: 8659

Answers (5)

Pmax
Pmax

Reputation: 175

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;

Upvotes: 1

Alex
Alex

Reputation: 5668

Can it be, that you have this issue?

Upvotes: 0

actual
actual

Reputation: 2370

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;

Upvotes: 11

RRUZ
RRUZ

Reputation: 136431

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.

Upvotes: 2

Bruce McGee
Bruce McGee

Reputation: 15334

Replace this line:

  title : pansichar;

with this:

  title: array[0..255] of Char;

Upvotes: 3

Related Questions