Search code examples
delphitimerfiremonkeyvcldelphi-10-seattle

How can I create an internal timer that will work with VCL and FMX?


I have a class that requires a timer. The class must work with both VCL and FMX. Unfortunately, the FMX timer is declared in FMX.Types and the VCL timer in Vcl.ExtCtrls.

As there is no conditional define like {$IFDEF FMX}xxx{$ENDIF} how do I use a timer in a cross platform class?


Solution

  • If it was me I would write a dedicated cross platform timer class that was independent of the FMX and VCL frameworks. Conceptually it would sit at the same level as the Delphi RTL.

    If you don't want to do that and want to re-use the existing timer classes then you are in a bind. For targets which don't have the VCL, what do you do? There's no way for you to know whether your code will be consumed by an FMX or VCL project. Think about it. You can compile your unit to a .dcu and include it in any project. At the time when the unit is compiled it cannot know the type of project that will ultimately consume it.

    So what to do? You could use the FMX timer everywhere. But that forces FMX onto VCL projects. I know I wouldn't like that. You could use the FMX timer everywhere other than Windows and use the VCL timer there. But that forces the VCL onto Windows FMX projects.

    So you might take this approach:

    1. Create your own cross-platform timer class.
    2. On platforms other than Windows implement it on top of the FMX timer.
    3. On Windows implement it using the raw Windows API functions SetTimer and KillTimer.