Delphi: OnTimer event of my own timer never happens

I need a timer in a Delphi block "without a form" (there is still a main block with a form), so I do this:

unit ... interface type TMyTimer = Class(TTimer) public procedure OnMyTimer(Sender: TObject); end; var MyTimer: TMyTimer; implementation procedure TMyTimer.OnMyTimer(Sender: TObject); begin ... end; initialization MyTimer := TMyTimer.Create(nil); with MyTimer do begin Interval := 1000; Enabled := True; OnTimer := OnMyTimer; end; finalization FreeAndNil(MyTimer); 

The problem is that the OnMyTimer procedure never starts. I will really appreciate any ideas as to why :-)

+7
timer delphi delphi-7
source share
3 answers

Besides the fact that you created MyTimer and freed up a MouseTimer , I don't see anything wrong with your code (I assume that you are using your code in a GUI application or at least have a message loop)

This code sample works with Delphi 5. Hello World written to the event log every second.

 unit Unit2; interface uses extctrls; type TMyTimer = Class(TTimer) public procedure OnMyTimer(Sender: TObject); end; var MyTimer: TMyTimer; implementation uses windows, sysutils, classes; procedure TMyTimer.OnMyTimer(Sender: TObject); begin OutputDebugString(PChar('Hello World')); end; initialization MyTimer := TMyTimer.Create(nil); with MyTimer do begin Interval := 1000; Enabled := True; OnTimer := OnMyTimer; end; finalization FreeAndNil(MyTimer); end. 
+6
source share

For the timer to work, your program must process messages . In the GUI program, this part is automatic; the TApplication class provides this for you. But you say that you have a "formless" program, so I assume that you are probably not calling Application.Run in your DPR file.

To use the timer, you need to process the messages. A typical starting point for a message pump is this code:

 while Integer(GetMessage(Msg, 0, 0, 0)) > 0 do begin TranslateMessage(Msg); DispatchMessage(Msg); end; 

When the timer expires, the OS effectively places the wm_Timer message in the program message queue. The GetMessage call GetMessage messages out of the queue, and DispatchMessage calls the destination window window procedure. TTimer creates a hidden window for itself to serve as a target for these messages, and DispatchMessage ensures that they get there.

+9
source share

Is your unit used by other units or not? If this device is not used by others, it will not even fall into the initialization section. Or perhaps the device will be completed sooner than you think.

Place a breakpoint in MyTimer: = TMyTimer.Create (nil); line and line FreeAndNil (MyTimer) and run the application. Make sure the timer is created when you want it not to be destroyed too early.

+1
source share

All Articles