Board index » delphi » Interrupting a process by pressing a cancel button

Interrupting a process by pressing a cancel button

How do I allow the user to interrupt a process by pressing a cancel button
on my form.  for instance, say they press the OK button to start a process,
and I execute the following code:

While not MyTable.EOF do
Begin
    {do something with the file...}
    {Somehow, I want to detect the user pressing the cancel button, and if
they
        pressed the cancel button, break out of this loop}
    MyTable.Next;
    Application.ProcessMessages;
end;

Any help is appreciated.

Thanks,
Jesse

 

Re:Interrupting a process by pressing a cancel button


One way that I've often found works out real well is by
using a semaphore.

For example:

(somewhere above on your form, declare a global variable of boolean
type called 'HitCancel', and default it to false)

Procedure TForm1.OnCancelClick(Sender: TObject);
Begin
  HitCancel := True;
End;

...
...
(your code for processing the records)
While (not MyTable.EOF) and (not HitCancel) do
Begin
  {do something}
  MyTable.Next;
  Application.ProcessMessages;
End;

if HitCancel then   // user hit the cancel button - clean-up routine
 Begin
   ( clean up in-progress stuff here )
 end;

Explanation:
    The processmessages function allows your form to accept the mouse-click
on the cancel button. Once the user hits cancel, they trigger the setting of
the
'HitCancel' semaphore. your loop, operating independantly of the cancel
button,
checks the status of the 'HitCancel' semaphore each time it finishes one
record, so
when someone hits cancel, the loop should terminate itself. You can also add
code
to 'clean up' your operation by doing the above clean-up code.

Hope this helps.

Quote
Jesse Castleberry wrote in message ...
>How do I allow the user to interrupt a process by pressing a cancel button
>on my form.  for instance, say they press the OK button to start a process,
>and I execute the following code:

>While not MyTable.EOF do
>Begin
>    {do something with the file...}
>    {Somehow, I want to detect the user pressing the cancel button, and if
>they
>        pressed the cancel button, break out of this loop}
>    MyTable.Next;
>    Application.ProcessMessages;
>end;

>Any help is appreciated.

>Thanks,
>Jesse

Re:Interrupting a process by pressing a cancel button


Another approach (beside the one I just replied to), which I think
is the more robust way to deal with it, is to create your own derivative
TThread
which, when activated, does your file processing. Once that thread is
running,
you can create an event-handler to clean things up when it is terminated.
The
Cancel button could simply call the terminate method in your thread to stop
the
processing.

[quote snipped]

Other Threads