Link to home
Start Free TrialLog in
Avatar of Bandit999
Bandit999

asked on

How do I interrupt a thread?

This should be simple... But I cannot get it to work.

This is in Delphi 7 - I've got 2 units, unit1 & unit2 with form1 and form2. Form1 has a single button 'Start'. Form2 has a progress bar and a button 'Cancel'.

Unit1.pas
procedure TForm1.StartClick(Sender: TObject);
var
  i : integer;
begin
  Form2.Show;
  for i := 1 to 1000000 do
     begin
       Form2.ProgressBar1.Position := Form2.ProgressBar1.Position + 1;
       Form2.Update;
     end;
end;

Unit2.pas
procedure TForm2.CancelClick(Sender: TObject);
begin
  Form2.Close;
end;

This is a very simplified example of what I have in my application - on running, Form1 shows - the Start button is clicked which starts a lengthy routine where I need to show the progress - so I show Form2 with a progress bar. What I want to do is be able to give the users the option of cancelling the routine by clicking on the cancel button on Form2. Trouble is that despite Form2 having focus it receives no events - specifically the CancelClick event never gets activated and so I can never escape from the routine.

How do I impliment this correctly? Thanks.
ASKER CERTIFIED SOLUTION
Avatar of BJThomsen
BJThomsen

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mocarts
mocarts

hi, Bandit :)

there are at least two ways to achieve what you need - repeatedly call Application.ProcessMessages in your processing routine or place your lengthy routine in separate thread and call TThread's Terminate in your Form2.Button1Click method.

wbr, mo.
Avatar of Bandit999

ASKER

Thanks for the replies - it was the Application.ProcessMessages bit that I was missing. By repeatedly calling that I can now interrupt OK.