在回调函数中使用with结构导致界面无响应
本帖最后由 xxyxxb 于 2012-01-09 10:17:11 编辑
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
lst1: TListBox;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetTitle(Hwnd: THandle; Param: Pointer): Boolean; stdcall;
var
Form1: TForm1;
implementation
{$R *.dfm}
function GetTitle(Hwnd: THandle; Param: Pointer): Boolean; stdcall;
var
Text: String;
begin
SetLength(Text, 100);
GetWindowText(Hwnd, PChar(Text), 100);
Text := PChar(Text);
if Text <> '' then
begin
//=============================问题代码=====================================
//用With结构会导致界面死掉
with Form1.lst1.Items do
begin
Add(IntToStr(Hwnd) + ':' + Text);
end;
//=============================问题代码=====================================
//正常
Form1.lst1.Items.Add(IntToStr(Hwnd) + ':' + Text);
end;
Result := True;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
EWProc: TFNWndEnumProc;
begin
EWProc := @GetTitle;
EnumWindows (EWProc, 0);
end;
end.
[解决办法]
with Form1.lst1.Items do
begin
Add(IntToStr(Hwnd) + ':' + Text);
end;
with中的Text实际上是Form1.lst1.Items.Text,即function TStrings.GetTextStr: string;
此函数中有两个for循环,都遍历了ListBox中的所有条目,调用Get逐一取了每个条目的内容,其中Get是
function TListBoxStrings.Get(Index: Integer): string;
此函数中调用两次SendMessage,先后发送LB_GETTEXTLEN和LB_GETTEXT!