| | | | in a DLL, so that Windows can inject (map) that DLL into the address space of Process B. (We will discuss DLL injection in detail in Chapter 20, DLL Injection and Foreign Process Access.) Unfortunately, this takes global hooks out of the realm of Visual Basic, because we cannot write a traditional DLL in VB. | | | | | | Thus, a global hook can potentially cause the injection of a DLL into every existing process space. Fortunately, if the DLL can be loaded at its default base address in each case, then it is not necessary to commit additional physical memory to a new virtual instance of the DLL. | | | | | | Also, the official documentation is a little vague as to when these DLLs will be released. Clearly, a process will not call the API function FreeLibrary to unload a DLL that it is not aware is even loaded! However, Richter says in his book: | | | | | | When a thread calls the UnhookWindowsHookEx function, the system cycles through its internal list of processes into which it had to inject the DLL and decrements the DLL's lock count. When this lock count reaches 0, the DLL is automatically unmapped from the process's address space. | | | | | | Indeed, some experimentation seems to bear this out. Injected DLLs appear to disappear in a ghostly fashion when no longer needed. Nevertheless, global hooks should be used with circumspection. | | | | | | Our plan now is to discuss the general principles of Windows hooks and then implement a thread-specific hook entirely within VB. Then, with the help of a simple DLL written in VC++, we will implement a global hook. In Chapter 20, we will discuss the process of DLL injection in more detail. | | | | | | To set a Windows hook, we use the SetWindowsHookEx function: | | | | | | HHOOK SetWindowsHookEx( int idHook, // type of hook to install HOOKPROC lpfn, // address of hook procedure HINSTANCE hMod, // handle to application instance DWORD dwThreadId // identity of thread to install hook for ); | | | | | | Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" ( ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long _ ) As Long | | | | | | If successful, the SetWindowsHookEx function returns a handle to the newly created hook. The idHook parameter specifies the type of hook to install. We will | | |