procedure Delay(MSecs: Longint);
//延时函数,MSecs单位为毫秒(千分之1秒)
var
  FirstTickCount, Now: Longint;
begin
  FirstTickCount := GetTickCount();
  repeat
    Application.ProcessMessages;
    Now := GetTickCount();
  until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;
正常情况下点击Button1执行延时及相关操作.
procedure TForm1.Button1Click(Sender: TObject);
begin
     ListBox1.Items.Add(datetimetostr(now()));
     Delay(40000);
     Label1.Caption :=inttostr(strtoint(Label1.Caption)+1);
     ListBox1.Items.Add(datetimetostr(now()));
end;但,想实现当点击Button1后,系统正在延时,如用户点击Button2时,就中止延时,直接执行Delay后面那两句:
  Label1.Caption :=inttostr(strtoint(Label1.Caption)+1);
  ListBox1.Items.Add(datetimetostr(now()));
procedure TForm1.Button2Click(Sender: TObject); 要如何写?

解决方案 »

  1.   

    var StopDelay:Boolean;
    procedure Delay(MSecs: Longint);
    //延时函数,MSecs单位为毫秒(千分之1秒)
    var
      FirstTickCount, Now: Longint;
    begin
      StopDelay := False;
      FirstTickCount := GetTickCount();
      repeat
        Application.ProcessMessages;
        Now := GetTickCount();
      until StopDelay or (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
    end;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
         ListBox1.Items.Add(datetimetostr(now()));
         Delay(40000);
         Label1.Caption :=inttostr(strtoint(Label1.Caption)+1);
         ListBox1.Items.Add(datetimetostr(now()));
    end;procedure TForm1.Button2Click(Sender: TObject);
    begin
      StopDelay := True;
    end
      

  2.   

    可以定义一个全局变量:temp:boolean=false;procedure Delay(MSecs: Longint);
    //延时函数,MSecs单位为毫秒(千分之1秒)
    var
      FirstTickCount, Now: Longint;
    begin
      if temp then exit;
      FirstTickCount := GetTickCount();
      repeat
        Application.ProcessMessages;
        Now := GetTickCount();
      until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
    end;
    procedure TForm1.Button2Click(Sender: TObject); 要如何写?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    temp:=not temp;
      

  3.   

    搞错了...^_^if temp then exit;//这句不要
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
    until temp or (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);