我枚举出窗口列表,但是发送的消息始终无法到达目标窗口,不知道哪里有问题
unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    B1: TButton;
    E1: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    T1: TTimer;
    B2: TButton;
    L1: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure B1Click(Sender: TObject);
    procedure T1Timer(Sender: TObject);
    procedure B2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;implementation{$R *.dfm}
function GetText(Wnd : HWND) : string;
var
  textlength : integer;
  text : PChar;
begin
  textlength:=SendMessage(Wnd,WM_GETTEXTLENGTH,0,0);
  if textlength=0 then
    Result := ''
  else begin
    getmem(text,textlength+1);
    SendMessage(Wnd,WM_GETTEXT,textlength+1,Integer(text));
    Result:=text;
    freemem(text);
  end;
end;function EnumWindowsProc (Wnd: HWND; LParam: LPARAM): BOOL; stdcall;
var
  st:string;
begin
  Result := True;
  //if (IsWindowVisible(Wnd)) and (GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) and (GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW = 0) then begin
  if (GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) and (GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW = 0) then begin
    st:=GetText(Wnd);
    IF not(st='') THEN
        Form1.Listbox1.items.add(st);
  end;
end;procedure TForm1.FormCreate(Sender: TObject);
var
  Param : Longint;
begin
  Form1.Listbox1.Clear;
  Param := 0 ;
  EnumWindows(@EnumWindowsProc , Param);end;
    
procedure TForm1.B1Click(Sender: TObject);
begin
    T1.Interval:=StrToInt(E1.Text)*1000;
    T1.Enabled := TRUE;
    L1.Caption :='目前状态:激活';
end;procedure TForm1.B2Click(Sender: TObject);
begin
    T1.Enabled := FALSE;
    L1.Caption :='目前状态:中止';
end;procedure TForm1.T1Timer(Sender: TObject);
var
  Handle: Integer;
  Param : Longint;
begin
    Handle := FindWindow(nil,pchar(Form1.listbox1.Items[listbox1.ItemIndex]));
    if Handle<>0 then
    begin
        SendMessage(Handle,WM_KEYDOWN,VK_RETURN,0);
        SendMessage(Handle,WM_KEYUP,VK_RETURN,0);
    end;end;
 
end.

解决方案 »

  1.   

    按键精灵等软件不是用的直接给窗口发消息的方式实现的。
    一般都是用API函数mouse_event 和keybd_event函数
      

  2.   

    以下是我随手写的:功能是点击“开始”菜单。
    procedure TForm1.Button1Click(Sender: TObject);
    var
      x, y: integer;
    begin
      Sleep(500);
      x := 20;
      y := Screen.Height - 10;
      SetCursorPos(x, y);
      mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
    end;