Declare a private field of your form like this:
FCancelLoop: Boolean;
Set the variable to False
before you start your loop. In the OnClick
event handler of your close button, set FCancelLoop
to True
. Check the value of FCancelLoop
inside the loop and break out of the loop if you find it is True
.
FCancelLoop := False;
while iCountDown > 0 do
begin
Application.ProcessMessages;
if FCancelLoop then
exit; // or perhaps break, but you get the idea
dec(iCountDown);
lblOutput.Caption := IntToStr(iCountDown);
Sleep(1000);
end;
However, this code has other problems. It uses the notorious Application.ProcessMessages
which has a tendency to make your life more complicated than you want it to be. Are your event handlers protected against re-entrancy? And the call to Sleep
on your main thread blocks that thread and makes it unresponsive. You really don't want that.
A better solution to your problem is to run your countdown loop with a timer.