Technical Exchange, DH explanation.
I used a thread to implement the timer function. Now let's see how the built-in timer of Delphi is implemented?
Actually, do not readCodeI also know how it works?
1 settimer and killtimer two APIs to control timer startup and Shutdown
2. Respond to the wm_timer message to execute user events.
Because timer is an invisible control, it should be inherited from tcomponent, but tcomponent does not have the ability to process messages, that is, we need to manually create a form process and assign it to it.
Let's talk about the Code as follows:
Ttimer = Class (tcomponent) Private // Interval Finterval: Cardinal; // Handle for receiving messages Fwindowhandle: hwnd; // User event Fontimer: tpolicyevent; fenabled: Boolean; // When the property is set, the timer is updated. // Kill the existing one and create a new one Procedure Updatetimer; // Setter Procedure Setenabled (value: Boolean ); Procedure Setinterval (value: Cardinal ); Procedure Setontimer (value: tpolicyevent ); // Form Process Procedure Wndproc ( VaR MSG: tmessage); protected Procedure Timer; dynamic; {$ if defined (CLR)} strict protected Procedure Finalize; override; {$ ifend} public Constructor Create (aowner: tcomponent); override; Destructor Destroy; override; published property enabled: Boolean read fenabled write setenabled default true; property interval: Cardinal read finterval write setinterval default 1000; property ontimer: tpolicyevent read fontimer write setontimer; End ;
Let's look at the key methods updatetimer and wndproc form process.
Procedure Ttimer. updatetimer; Begin If Fwindowhandle <> 0 Then Killtimer (fwindowhandle, 1 ); If (Finterval <> 0) And Fenabled And Assigned (fontimer)Then Begin If Fwindowhandle = 0 Then // Allocate a handle to process the message Fwindowhandle: = allocatehwnd (wndproc ); If Settimer (fwindowhandle, 1, finterval, Nil ) = 0 Then Raise eoutofresources. Create (snotimers ); End Else If Fwindowhandle <> 0 Then Begin Deallocatehwnd (fwindowhandle ); // Cancel the handle to process the message Fwindowhandle: = 0; End ; End ;
What have you done in the Form Process?
ProcedureTtimer. wndproc (VaRMSG: tmessage );BeginWithMSGDoIfMSG = wm_timerThenTry timer; timer t application. handleexception (Self );EndElse// Other messages, which are processed in Windows by defaultResult: = defwindowproc (fwindowhandle, MSG, wparam, lparam );End;
What is the timer method? By the way, user events are executed.
ProcedureTtimer. timer;BeginIfAssigned (fontimer)ThenFontimer (Self );End;
It's also very simple. Let's take a look at how the controls are compiled.
My name is DH.