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 T
Your code does not work because TTimer
component internally uses WM_TIMER
message processing and a console app does not have a message loop. To make your code work you should create a message pumping loop yourself:
program TimerTest;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows,
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;
procedure MsgPump;
var
Unicode: Boolean;
Msg: TMsg;
begin
while GetMessage(Msg, 0, 0, 0) do begin
Unicode := (Msg.hwnd = 0) or IsWindowUnicode(Msg.hwnd);
TranslateMessage(Msg);
if Unicode then
DispatchMessageW(Msg)
else
DispatchMessageA(Msg);
end;
end;
begin
EventHandlers := TEventHandlers.Create();
Timer := TTimer.Create(nil);
Timer.Enabled := false;
Timer.Interval := 1000;
Timer.OnTimer := EventHandlers.OnTimerTick;
Timer.Enabled := true;
MsgPump;
end.