Search code examples
delphi

How to pause program execution until button press?


I've got an algorithm. I'd like to pause it at some point and then continue once the user presses a button. How do I do that? I've browsed the documentation, and searched the internet, but no luck yet.

Here's a relevant code snip:

      if A[i]>A[i+1]
        then
          begin
            Zameni(i,i+1);
            done:=true;

            sleep(pauza);

            br:=br+1;
          end;

Right now, I use sleep (pauza is just a constant, means pause in Serbian). Ideally, I'd like to replace that line with a procedure which would sleep for the interval, or wait for a button press based on a configuration setting.

EDIT1: Ah yes, if it wasn't obvious - it's a graphics application, not console, so slapping a "readln" won't work (sadly).


Solution

  • I wouldn't recommend it as good application design, but if none of the other suggestions are suitable for you, you may prefer this.

    Add a 'Paused: Boolean' field to your class/form, and a 'Continue' button.

    When you start the operation, set Paused to False, and Continue.Enabled := False;

    When your code reaches the section where you want to pause:

    Paused := True;
    Continue.Enabled := True;
    while Paused do
    begin
      sleep(100);
      Application.ProcessMessages;
    end;
    

    In your Continue buttons event handler:

    procedure Form1.ContinueClick(Sender: TObject);
    begin
      Paused := False;
      Continue.Enabled := False;
    end;
    

    As I said before, not pretty, but it should get the job done.