开发者

delphi 7 timer reset

How could one reset the TTimer1 so even ontimer triggers, and the count restarted?

The Question i开发者_运维知识库s 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;


There's no way to do it in design time. Have the handler disable the TTimer then re-enable it.


Resetting a TTimer to re-trigger its event is simple. When you disable and enable the TTimer, your timertimeout event will re-trigger based on its time interval you set. For instance,

Timer1.interval:=1000; //milliseconds
Timer1.enabled:=false;
Timer1.enabled:=true;

Timer1 event will fire when one second is up the next time you enable and disable the timer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜