Mega Code Archive

 
Categories / Delphi / Examples
 

Using a keystroke to abort a long loop

Title: Using a keystroke to abort a long loop Question: Sometimes we have a very time-consuming loop, and would like to allow the user to abort its processing. How can we do it? Answer: The following demosntrates how can you detect a keypress during a loop, and interrupt it. Of course, you will substitute the example loop with a more useful code, in a real world application ;-) procedure TForm1.Button1Click(Sender: TObject); var i: Integer; begin for i:= 0 to 9999999 do begin Self.Caption := Format('Iteration #%d', [i]); //allow the app to process messages during the loop; //otherwise, we couldn't check if a key is pressed: Application.ProcessMessages; //if ESC is pressed, abandon loop: if GetKeyState(VK_ESCAPE) and 128 = 128 then Break; end; //for end;