How could one reset the TTimer1 so even ontimer triggers, and the count restarted?
The Question is for Design Time command to act on Run-time.
I suppose you actually mean that
var
Timer1: TTimer;
Then, to reset the timer, do
Timer1.Enabled := false;
Timer1.Enabled := true;
In my "RejbrandCommon.pas" standard library, I have actually defined
procedure RestartTimer(Timer: TTimer);
begin
Timer.Enabled := false;
Timer.Enabled := true;
end;
Then, every time I need to restart I timer, I just do
RestartTimer(Timer1);
Of course, if you want the OnTimer procedure (e.g. Timer1Timer) to trigger prior to restart, you have to do
Timer1.OnTimer(Self);
Timer1.Enabled := false;
Timer1.Enabled := true;
or define
procedure TriggerAndRestartTimer(Timer: TTimer);
begin
Timer.OnTimer(nil);
Timer.Enabled := false;
Timer.Enabled := true;
end;
(Of course, the last procedure, TriggerAndRestartTimer, is not a method, and hence there is no Self. However, most likely the Timer1Timer procedure doesn't care about the Sender property, so you can send just anything, such as nil instead of Self.)
This is a correction to Andreas' answer: if you call his RestartTimer on a timer that was disabled, it will (accidentally) enable that timer. So, here is the fix: the ResetTimer procedure.
procedure ResetTimer(Timer: TTimer);
VAR OldValue: Boolean;
begin
OldValue:= Timer.Enabled;
Timer.Enabled:= FALSE; { Stop timer }
Timer.Enabled:= OldValue; { Start the timer ONLY if was enabled before }
end;
or
procedure ResetTimer(Timer: TTimer);
begin
if NOT Timer.Enabled then EXIT;
Timer.Enabled:= FALSE; { Stop timer }
Timer.Enabled:= TRUE; { Start the timer ONLY if was enabled before }
end;
For those who really want to RESTART the timer then Andreas' procedure is just fine.
And here is the final/proper answer:
UNIT cvTimer;
{----------------------
Better Timer
------------------------------------}
INTERFACE {$WARN UNIT_PLATFORM OFF}
USES
System.Classes, Vcl.ExtCtrls;
TYPE
TMyTimer= class(TTimer)
private
public
procedure Reset;
end;
IMPLEMENTATION
procedure TMyTimer.Reset;
begin
if NOT Enabled then EXIT;
Enabled:= FALSE; { Stop timer }
Enabled:= TRUE; { Start the timer ONLY if was enabled before }
end;
procedure Register;
begin
RegisterComponents('3rdParty', [TMyTimer]);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With