在回调函数中使用with结构导致界面无响应
- Delphi(Pascal) code
unit Unit1;interfaceuses 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结构导致程序界面无响应,不使用的话,一切正常
开发平台: Delphi 7 + Win7
问题:难道回调函数中还有什么限制么?
[解决办法]
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!