Is it possible to show the countdown of a TTimer in a Label ? Like instantly putting the variable in the Label Caption. I was thinking about how I could do, I'm trying to do a visible countdown in the Form.
Delphi : Show a TTimer
1.8k views Asked by Mike C At
2
There are 2 answers
2
On
Let's grab the FCount
variable and keep the things simple.
Here the timer stops itself when the count reaches 0
.
procedure TForm1.FormCreate(Sender: TObject);
begin
FCount := 10;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
label1.Caption := IntToStr(FCount);
Dec(FCount);
if FCount < 0 then begin
FCount := 10;
Timer2.Enabled := False;
end;
end;
The following uses an approach based on the TThread
class which avoids to grab the FCount
variable from the Andreas Rejbrand's answer
procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.CreateAnonymousThread(procedure
var
countFrom, countTo: Integer;
evt: TEvent;
begin
countFrom := 10;
countTo := 0;
evt := TEvent.Create(nil, False, False, '');
try
while countTo <= countFrom do begin
TThread.Synchronize(procedure
begin
label1.Caption := IntToStr(countFrom);
end);
evt.WaitFor(1000);
Dec(countFrom);
end;
finally
evt.Free;
end;
end).Start;
end;
As Ken White said, a
TTimer
doesn't have a 'countdown'. However, of course it is possible to implement a 'countdown' in your application. The following is an example of one way of doing this.Create a new VCL application.
Add a private integer variable named
FCount
to your form class.Use the following code as your form's
OnCreate
event handler:OnPaint
event handler:TTimer
to your form, and use the following code as itsOnTimer
handler:Call the
Invalidate
method in the form'sOnResize
handler.Run the application.