Anonymous Timer and FireMonkey

I guess that everyone knows the good old timer and its OnTimer event. There is a timer for the VCL and for FireMonkey as well which are nearly similar.
In both timers there is one thing missing: I would like to use an anonymous method for the OnTimer event instead of the old TNotifyEvent. The reason for this is that anonymous methods capture variables.
Since Delphi doesn’t offer this feature let’s implement it ourself.
Let’s start with a new unit and we will derive from the existing TTimer.

I’m using the same classname for the new timer because then it is possible to use it without registering a new component. I will show this trick later.
First, let’s add a property for the anonymous method.

After we added the new property we have to call it. That’s why I will override the DoOnTimer method.

Now, we have a small problem: Delphi only creates the underlying timer object of the operation system if the OnTimer event of a TTimer is assigned. You can see this in the unit FMX.Types.

That’s why we need a dummy OnTimer event.

Okay, that’s it. Now we have a TTimer with an anonymous method. I guess we should use it then. 🙂

We simply create a form, put two labels and a normal timer on it. Then we add the unit FMX.Types.AnonymousTimer to the uses clause after the unit FMX.Types. The designer now creates a normal timer and we can set all the normal timer properties.

At runtime the compiler replaces the normal timer with our new one because the last unit in the uses clause has the highest visibility. This trick only works because we added no published properties to our new timer component.

The result is a label which shows the expired seconds until 100.

This entry was posted in FireMonkey, Tips and Tricks and tagged , . Bookmark the permalink.

2 Responses to Anonymous Timer and FireMonkey

  1. Arrancamos says:

    Nice trick!

    That was with XE5, how about XE10.2 berlin, any way yo improve your code? I’m c++ builder dev. Regards.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.