实现思路分析:
1、找到目标程序的句柄,可以通过窗口的caption属性获取,使用
FindWindow(nil, 'app caption');
2、找到你要控制的组件,如Button,使用
FindWindowEx(ParentHandle, 0, nil, 'btn caption');
3、发送Windows消息控制目标程序
SendMessage( HEdt, BM_CLICK, 0, 0 );
下面是实现该功能的Delphi代码:
unit Unit1;
Interface usesinterface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = Class (class(TForm)
btn1: TButton;
mmo1: TMemo;
edt1: TEdit;
edt2: TEdit;
btn3: TButton;
lbl1: TLabel;
lbl2: TLabel;
btn4: TButton;
procedure btn1Click(Sender: TObject);
procedure btn3Click(Sender: TObject);
procedure btn4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
ShellAPI;
{$R *.dfm}
var
HApp,
HEdt : THandle;
procedure TForm1.btn1Click(Sender: TObject);
begin
HApp := FindWindow(nil, PAnsiChar(edt1.text));
mmo1.Lines.Add(IntToStr(HApp));
HEdt := FindWindowEx(HApp, 0, nil, PAnsiChar(edt2.text));
mmo1.Lines.Add(IntToStr(HEdt));
SendMessage( HEdt, BM_CLICK, 0, 0 );
end;
procedure TForm1.btn3Click(Sender: TObject);
begin
ShellExecute(handle, 'open', 'otherapp.exe',nil,nil, SW_SHOWNORMAL{SW_SHOWMAXIMIZED});
end;
procedure TForm1.btn4Click(Sender: TObject);
begin
SendMessage( HApp, WM_CLOSE, 0, 0 );
end;
end.