How do I prevent DLL injection
Solution 1:
The best technical solution would be to do something that causes the loader code to not be able to run properly after your process initializes. One way of doing this is by taking the NT loader lock, which will effectively prevent any loader action from taking place. Other options include patching the loader code directly in memory to make calls to LoadLibrary fail for the attacker (e.g. insert an int3 breakpoint and self-debug to handle expected cases)..
But speaking as a hacker (one who admins the site you linked to, in fact), you're not going to ever stop people from getting code into your process, one way or another. LoadLibrary just happens to be a handy shortcut, but there are tons of different ways to load code manually that you could never hope to stop entirely, short of some extremely involved ring0 code. And even if you do go to ring0, the hackers will be right there beside you.
Also, there are plenty of legitimate uses for DLL injection. Theme programs, accessibility tools, and various programs that extend OS functionality can all potentially use DLL injection to give added functionality to any program.
Solution 2:
How to defend against those 3 techniques:
CreateRemoteThread
You can prevent the first technique (CreateRemoteThread which calls LoadLibrary) by hooking LoadLibrary. In your hook you check against a list of DLL names that you know are part of the process and that may be loaded, or you can check against a list of known DLLs you don't want to load.
When you find a DLL you don't want to load SetLastError(ERROR_ACCESS_DENIED) then return NULL. I set the last error so that people that write code looking for an error code get one. This appears to work, perhaps a different code may be more appropriate.
That will stop the DLL from loading.
SetWindowsHookEx
I think the same technique for CreateRemoteThread blocking will work for SetWindowsHookEx, but only if you can get your hook installed before the SetWindowsHookEx technique has started loading its code (which is typically when the first Window is created in an app - so early in its lifetime).
Code Cave
Nice technique. Not seen that before. You can defend against this, but you'll have to hook the LoadLibrary entry point (not the IAT table) as the Code Cave calls LoadLibrary directly.
As the author of the article commented - there are many ways you can be attacked and you probably will have a hard time defeating them all. But often you only want to defend against certain DLL loads (such as a particular 3rd party DLL that is incompatible with your software because the 3rd party DLL wasn't written properly to accomodate the fact that another hook may also be present, so you block it from loading).