Mega Code Archive

 
Categories / Delphi / Examples
 

Why freeze you program Allow the user to cancel a long process!

Title: Why freeze you program? Allow the user to cancel a long process! Don't freeze your program. If your main thread goes in a loop, your application will be frozen. What if the user want to cancel the running activity? So make it a thread and make the termination of the loop depend on the value of a variable (FCanceled in this tip) which can be modified by the user (with Button2 in this tip). When the user click on Button2, FCanceled becomes False and the thread's loop ends. During the loop, you can right click the title bar to show the system menu, you can drag the form, and all other things without pausing the loop. ---------------- unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } FCanceled: Boolean; public { Public declarations } end; TThread1 = class(TThread) protected constructor Create; procedure Execute; override; procedure IncreaseNumber; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin Self.Caption := 'You May Cancel a Loop'; Edit1.Text := '1'; Edit1.ReadOnly := True; Button1.Caption := 'Start'; Button2.Caption := 'Stop'; end; procedure TForm1.Button1Click(Sender: TObject); begin FCanceled := False; TThread1.Create; end; procedure TForm1.Button2Click(Sender: TObject); begin FCanceled := True; end; constructor TThread1.Create; begin inherited Create(false); end; procedure TThread1.Execute; var success: Boolean; begin Self.Priority := tpLowest; with Form1 do begin while not FCanceled do begin // call Synchronize so that you can create more threads by clicking // the Start button and all created threads can run synchronously :) Synchronize(IncreaseNumber); end; end; end; procedure TThread1.IncreaseNumber; begin with Form1 do Edit1.Text := IntToStr(Succ(StrToInt(Edit1.Text))); end; end.