As the question subject says. I have a console application in Delphi, which contains a TTimer variable. The thing I want to do is assign an event handler to TTimer.OnTimer event. I am totally new to Delphi, I used to use C# and adding the event handlers to events is totally different. I have found out that one does not simply assign a procedure to event as a handler, you have to create a dummy class with a method which will be the handler, and then assign this method to the event. Here is the code I currently have:
program TimerTest;
{$APPTYPE CONSOLE}
uses
SysUtils,
extctrls;
type
TEventHandlers = class
procedure OnTimerTick(Sender : TObject);
end;
var
Timer : TTimer;
EventHandlers : TEventHandlers;
procedure TEventHandlers.OnTimerTick(Sender : TObject);
begin
writeln('Hello from TimerTick event');
end;
var
dummy:string;
begin
EventHandlers := TEventHandlers.Create();
Timer := TTimer.Create(nil);
Timer.Enabled := false;
Timer.Interval := 1000;
Timer.OnTimer := EventHandlers.OnTimerTick;
Timer.Enabled := true;
readln(dummy);
end.
It seems correct to me, but it does not work for some reason.
EDIT
It appears that the TTimer component won’t work because console applications do not have the message loop. Is there a way to create a timer in my application?
Your code does not work because
TTimercomponent internally usesWM_TIMERmessage processing and a console app does not have a message loop. To make your code work you should create a message pumping loop yourself: