Safe event hooking and unhooking (for Delphi IDE plugins)

In the comments to my Google+ post announcing my blog post on Hacking the Delphi 10 Project Options dialog Ondrej Kelle said:

If two or more plugins hijack the same global event handler then they must restore the previous (from their point of view) handler in reverse order, however this is not guaranteed and therefore this technique is likely to cause trouble.

and

API should be written, safe for plugins to use instead of the event handlers

to which Heinz Toskano added

This scenario remembers me when I wrote interrupt handlers for DOS. The civilized way was to hook and return the original handler, except when you replace the interrupt, in that case you was obliged to expose the original interface, just to not broke something else. Something similar must be done with IDE plugins, otherwise it will become bad coding.

I did a quick Google search but found no existing standard so I decided to simply describe one and publish it in the hope that others will find it useful and adhere to it.

NOTE:
I have moved the code and description to it’s own static page. I will improve it as I go along and blog about these improvements.

I post a link to this article on Google+. If you want to leave any comments, use this post.