How can I dynamically inject code into event handlers in Delphi?
- by mjustin
For debugging / performance tests I would like to dynamically add logging code to all event handlers of components of a given type.
For example, for all Dataset components located ona TDatamodule, I would like to add some code for the BeforeOpen and the AfterOpen event to store the start and end time and send a line to a logger with the elapsed time in the AfterOpen event.
I would prefer to do this dynamically (no component subclassing), so that I can add this to all existing datamodules and forms with minimal effort only when needed.
Iterating all components and filtering by their type is easy, but for the components which already have event handlers assigned, I need a way to store the existing event handlers, and assign a new modified event handler which first does the logging and then will invoke the original code which was already present.
Is there a design pattern which can be applied, or even some example code which shows how to implement this in Delphi?