使用下面这个程序可以获得其他窗体上的Tedit控件的值。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
Button2: TButton;
ListBox2: TListBox;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
function EnumWindowsProc( Hwnd: HWND;
MyForm: TForm1): Boolean;
stdcall;
//回调函数
function EnumChildControlProc( Hwnd: HWND;
MyForm: TForm1): Boolean;
stdcall;
//回调函数, 处理返回来的窗体控件的句柄
implementation
{$R *.dfm}
function EnumWindowsProc( Hwnd: HWND;
MyForm: TForm1): Boolean;
stdcall;
var
WndWindowText: array[0..254] of char;
//用来存储窗口名
begin
GetWindowText(Hwnd,WndWindowText,254);
MyForm.ListBox1.Items.Add('窗口名: '+StrPas(WndWindowText));
Result:= True;
end;
function EnumChildControlProc( Hwnd: HWND;
MyForm: TForm1): Boolean;
stdcall;
var
ComponentClassName, ComponentText: array[0..254] of char;
Buffer:array[0..255]of char;
begin
GetClassName(Hwnd,ComponentClassName,254);
GetWindowText(Hwnd, ComponentText, 254);
if StrPas(ComponentClassName)='TEdit' then
begin
SendMessage(Hwnd,WM_GETTEXT,256,Longint(@Buffer));
//使用 WM_GetText消息获得Tedit的值.
MyForm.ListBox2.Items.Add('TEdit的内容: '+StrPas(Buffer));
end;
Result:= True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ListBox1.Items.Clear;
EnumWindows(@EnumWindowsProc, Longint(self));
// 注册回调函数入口地址的函数
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Hwn: HWND;
begin
Form1.ListBox2.Items.Clear;
ListBox2.Items.Add('有如下控件名称');
Hwn:= FindWindow(nil,PChar(Label2.Caption));
if Hwn<>0 then
EnumChildWindows(Hwn,@EnumChildControlProc,LongInt(Self))
else
MessageBox(self.Handle,'没有获得该窗口句柄','提示',0);
end;
procedure TForm1.ListBox1Click(Sender: TObject);
begin
Label2.Caption:=Copy(ListBox1.Items.Strings[ListBox1.itemIndex],9,Length(ListBox1.Items.Strings[ListBox1.itemIndex]));
end;
end.