---
title: "关于Delphi中的application.ProcessMessages问题(处理事件)"
author: "cfeers"
date: "2011-03-22T17:28:01Z"
tags: []
categories: ["编程语言"]
slug: "delphi-application-processmessages"
draft: false
lastmod: "2011-03-22T17:28:01Z"
id: 970818
url: "https://cfeers.iteye.com/blog/970818"
---

关于Delphi中的application.ProcessMessages问题(处理事件)  
━━━━━━━━━━━━━━━━━━━━━━━━━━

很多资料中提到，Delphi中的application.ProcessMessages相当于VB中的Doevents函数(转让进程控制)，可是，在实际应用中，却不是这么回事。例：    
(VB   Code)    
Private   Sub   Command1\_Click()      
        Dim   i   As   Integer      
        Dim   j   As   Integer      
        Text1.Text   =   0      
        For   i   =   1   To   10000      
                For   j   =   1   To   10000      
                        DoEvents      
                        Text1.Text   =   Val(Text1.Text)   +   1      
                Next      
          Next    
End   Sub      
     
Private   Sub   Command2\_Click()      
          MsgBox   1      
          Unload   Me    
End   Sub    
\=================================================================    
(Delphi   Code)    
procedure   TForm1.Button1Click(Sender:   TObject);    
var   i,j:integer;    
begin      
          edit2.Text:='0';      
          for   i:=1   to   10000   do      
                  Begin      
                          for   j:=1   to   10000   do      
                                Begin      
                                        application.ProcessMessages;            
                                        edit1.Text:=inttostr(strtoint(edit2.text)+   1);      
                                end;      
                  end;    
end;    
     
procedure   TForm1.Button2Click(Sender:   TObject);    
begin      
        showmessage('1');      
        Close;    
end;    
\=================================    
当点击VB中的Command2按钮时，马上弹出消息框并关掉应用程序(或点窗体关闭键时会即时关掉程序)，可是，点Delphi中的Button2Click时，虽然也弹出消息框，可是应用程序并不关闭，仍在计算，即使点窗体关闭键也要计算完后才关掉。在一些情况下，可能要用到大循环，因此，要给用户提供随时中止程序的功能，那么，在Delphi中，如何才能实现?  
━━━━━━━━━━━━━━━━━━━━━━━━━━  
procedure   TForm1.Button2Click(Sender:   TObject);    
begin      
        showmessage('1');      
        Application.Terminate;     //改为这个。    
end;  
━━━━━━━━━━━━━━━━━━━━━━━━━━  
procedure   TForm1.Button1Click(Sender:   TObject);    
var   i,j:integer;    
begin      
          edit2.Text:='0';      
          for   i:=1   to   10000   do      
                  Begin      
                          for   j:=1   to   10000   do      
                                Begin      
                                        application.ProcessMessages;            
                                        if   Application.Terminated   then   Exit;    
                                        edit1.Text:=inttostr(strtoint(edit2.text)+   1);      
                                end;      
                  end;    
end;    
     
procedure   TForm1.Button2Click(Sender:   TObject);    
begin      
        showmessage('1');      
        Application.Terminate;    
end;