您的位置:首页 > 移动开发

Application.ProcessMessages

2009-04-07 20:20 211 查看
procedure TForm1.Button2Click(Sender: TObject);
var
I, J, X, Y: Word;
begin
I := 0;
J := 0;
while I < 64000 do
begin
Randomize;
while J < 64000 do
begin
Y := Random(J);
Inc(J);
Application.ProcessMessages;
end;
X := Random(I);
Inc(I);
end;
Canvas.TextOut(10, 10, 'The Button2Click handler is finished');
end;

代码中红色的一行的作用:

如果你运行一个非常耗时的循环,那么在这个循环结束前,你的程序可能不会响应任何事件,你按按钮没有反应,程序设置无法绘制窗体,看上去就如同死了一样,这有时不是很方便,例如于终止循环的机会都没有了。这时你就可以在循环中加上这么一句,每次程序运行到这句时,程序就会让系统响应一下消息,从而使你有机会按按钮,窗体有机会绘制。

//如果有这样一个循环, 是非常可怕的; 因为它完不了, 你得等着.
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to MaxInt do
begin
Text := IntToStr(i);
end;
end;

//即使这样也无济于事, 因为在循环期间你执行不了 Button2Click
var
b: Boolean;

procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
b := True;
for i := 0 to MaxInt do
begin
if b then Text := IntToStr(i) else Exit;
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
b := False;
end;

//如果在循环期间...
for i := 0 to MaxInt do
begin
if b then Text := IntToStr(i) else Exit;
{看看还有其他什么事情发生}
end;

//Application.ProcessMessages 就是干这个的!
var
b: Boolean;

procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
b := True;
for i := 0 to MaxInt do
begin
if b then Text := IntToStr(i) else Exit; Application.ProcessMessages; {!}
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
b := False;
end;

最近几天搞鼠标点击模拟时发现一旦循环次数过13就会出现form无响应,后来经高人指点了下,说用Application.ProcessMessages。但是很纳闷直接编译运行却可以,不会发生上面的情况,很奇怪~~望大牛指导下~~

Application.ProcessMessages作用:
运行一个非常耗时的循环,那么在这个循环结束前,程序可能不会响应任何事件,按钮没有反应,程序设置无法绘制窗体,看上去就如同死了一样,这有时不是很方便,例如于终止循环的机会都没有了,又不想使用多线程时,这时你就可以在循环中加上这么一句,每次程序运行到这句时,程序就会让系统响应一下消息,从而使你有机会按按钮,窗体有机会绘制。所起作用类似于VB中DoEvent方法.

Call ProcessMessages to permit the application to process messages that are currently in the message queue. ProcessMessages cycles the Windows message loop until it is empty, and then returns control to the application.
Note: Neglecting message processing affects only the application calling ProcessMessages, not other applications. In lengthy operations, calling ProcessMessages periodically allows the application to respond to paint and other messages.
Note: ProcessMessages does not allow the application to go idle, whereas HandleMessage does.

调用ProcessMessages来使应用程序处于消息队列能够进行消息处理,ProcessMessages将Windows消息进行循环轮转,直至消息为空,然后将控制返回给应用程序。
注示:仅在应用程序调用ProcessMessages时勿略消息进程效果,而并非在其他应用程序中。在冗长的操作中,调用ProcessMessages周期性使得应用程序对画笔或其他信息产生回应。
注示:ProcessMessages不充许应该程序空闲,而HandleMessage则然.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: