
Search

Support DFF
If you benefit from the website, in terms of
knowledge, entertainment value, or something otherwise useful,
consider making a donation via PayPal to help defray the
costs. (No PayPal account necessary to donate via credit
card.) Transaction is secure.
If you shop at Amazon anyway,
consider using this link. We receive a few cents from each purchase.
Thanks.

Contact
Feedback:
Send an e-mail with your
comments about this program (or anything else).

|
| |
Program loops often may run for extended periods - seconds, minutes or
even hours. In these cases, it is good coding practice to let the user
terminate the loop early. One way is described here:
- Allocate a Stop button with its visible property set to
false.
- In the Onclick event exit for the Stop button set tag
property to 1. The tag property is a "spare"
integer field in each control to be used as the programmer sees
fit. I usually use the TForm1.tag field, but
one of the button tags would work as well.
- Before entering the loop:
- Set tag to 0
- Make the Stop button visible
- Disable the Start button (Enabled:=false) so the user
cannot start a second copy of the loop while the first one is running.
- Either:
- Set screen.cursor to crHourglass or
- Loop through all controls setting all to crHourGlass
and then set the form cursor to crHourglass and the stop
button cursor to crArrow. This has the advantage of
showing a normal arrow cursor when the user moves the mouse over the
Stop button and the hourglass cursor everywhere else.
- Make a test for tag<>0 one of the terminating tests for
the loop.
- Within the loop call application.processmessages periodically,
probably once or twice per second is often enough. Application.processmessages
allows user actions, (such as clicking the stop button), to be
processed. Each call takes a bit of CPU time so there is a trade off
between responding to user clicks and loop speed. I usually test for
the loop counter being a multiple of 1024 or 4096 or some other power of
2 to trigger the test.
- Before exiting the Onclick event, reverse the above above steps.
Here's some sample code illustrating the technique.
procedure TForm1.StartBtnClick(Sender: TObject);
var
i:integer;
begin
tag:=0; {reset tag}
StopBtn.visible:=true;
StartBtn.enabled:=false;
{make
all cursors hourglass}
for I:= 0 to controlcount-1 do controls[i].cursor:=crhourglass;
cursor:=crhourglass;
StopBtn.cursor:=crArrow; {except the stop button}
{THE LOOP}
i:=0;
while (tag=0) and (i<high(i)) do
begin
inc(i);
if i mod 1024=0 then application.processmessages;
{do loop work here}
end;
{END LOOP}
Stopbtn.visible:=false;
StartBtn.enabled:=true;
for I:= 0 to controlcount-1 do controls[i].cursor:=crdefault;
cursor:=crdefault;
end;
procedure TForm1.StopBtnClick(Sender: TObject);
begin
tag:=1;
end;
|