To create a TTimer
at runtime in Delphi, you can use the following steps:
- Create a Form:
Create a new VCL Forms Application in Delphi.
- Add a Button and a Timer:
Drop a
TButton
and aTTimer
component onto the form from the Tool Palette. - Add Code to Create
TTimer
Dynamically:Add code to the form’s unit to create a
TTimer
dynamically when the button is clicked.123456789101112131415161718192021222324252627282930313233343536373839404142unit MainForm;interfaceusesWinapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;typeTForm1 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm1: TForm1;implementation{$R *.dfm}procedure TimerOnTimer(Sender: TObject);beginShowMessage(‘Timer event!’);end;procedure TForm1.Button1Click(Sender: TObject);varMyTimer: TTimer;begin// Create a TTimer dynamicallyMyTimer := TTimer.Create(Self);MyTimer.Interval := 1000; // Set the interval in milliseconds (e.g., 1000 ms = 1 second)MyTimer.OnTimer := TimerOnTimer;MyTimer.Enabled := True;end;end.In this example, clicking
Button1
dynamically creates aTTimer
with a specified interval and assigns an event handler (TimerOnTimer
) to theOnTimer
event. TheTimerOnTimer
procedure shows a message when the timer fires.Remember to adjust the code based on your specific requirements, including setting the desired interval and implementing your own logic in the
OnTimer
event handler.
Leave a Reply