天天看点

WinAPI: GetForegroundWindow - 获取前台窗口的句柄

WinAPI: GetForegroundWindow - 获取前台窗口的句柄

//声明:
GetForegroundWindow: HWND;


//举例:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    {先添加如下三个控件}
    Button1: TButton;
    Memo1: TMemo;
    Timer1: TTimer;

    procedure Timer1Timer(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  h: HWND; {把句柄定义成全局变量以避免重复}

{准备工作}
procedure TForm1.FormCreate(Sender: TObject);
begin
  Memo1.Align := alLeft;
  Memo1.ScrollBars := ssBoth;
  Timer1.Enabled := False;
  Timer1.Interval := 100;
end;

{启动与停止}
procedure TForm1.Button1Click(Sender: TObject);
begin
  Timer1.Enabled := not Timer1.Enabled;
  case Timer1.Enabled of
    True : Text := '开始截获';
    False: Text := '停止截获';
  end;
  Memo1.Clear;
end;

{定时获取}
procedure TForm1.Timer1Timer(Sender: TObject);
var
  p: array[0..254] of Char;
begin
  if h <> GetForegroundWindow then
  begin
    h := GetForegroundWindow;
    GetWindowText(h, p, 255);
    if p <> '' then Memo1.Lines.Add(p);
  end;
end;

end.
           

继续阅读