I wrote this little hook-engine for a much bigger article. Sometimes it seems such a waste to write valuable code for large articles whose topic isn't directly related to the code. This often leads to the problem that the code won't be found by the people who are looking for it.
Personally, I would've used Microsoft's Detour hook engine, but the free license only applies to x86 applications, and that seemed a little bit too restrictive to me. So, I decided to write my own engine in order to support x64 as well. I've never downloaded Detour nor have I ever seen its APIs, but from the general overview given by Microsoft it's easy to guess how it works.
As I said, this is only a part of something bigger. It's not perfect, but it can easily become such. Since this is not a beginner's guide about hooking, I assume that the reader already possesses the necessary knowledge to understand the material. If you never heard about this subject, you'd better start with another article. There's plenty of guides out there, no need to repeat the same things here.
As everybody knows there's only one easy and secure way to hook a Win32 API: to put an inconditional jump at the beginning of the code to redirect it to the hooked function. And by secure I just mean that our hook can't be bypassed. Of course, there are some other ways, but they're either complicated or insane or both. A proxy dll, for instance, might work in some cases, but it's rather insane for system dlls. Overwriting the IAT is unsecure for two reasons:
a) The program might use GetProcAddress to retrieve the address of an API (and in that case we should handle this API as well).
b) It's not always possible, there are many cases as for packed programs where the IAT gets built by the protection code and not by the Windows loader.
Ok, I guess you're convinced. Let's just say that there's a reason why Microsoft uses the method presented in this article.