Using VCL TTimer in Delphi console application

后端 未结 3 1996
走了就别回头了
走了就别回头了 2021-02-04 09:14

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

3条回答
  •  北海茫月
    2021-02-04 10:10

    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.
    

提交回复
热议问题