Implementing the WH_KEYBOARD Hook

When implementing any type of hook in VB.NET, you should follow the rules stated in Chapter 3 for setting up and using hooks. I noticed that if a hook is not removed before the application ends -- using the UnHookWindowsHookEx API function -- the application does not crash, as it normally would in a previous version of VB. However, I always incorporate code to remove a hook after it is installed.

Remember, you can install hooks on one thread at a time, or on every thread in the system. Therefore, if you create multiple threads in your application and you install a thread-specific hook, the hook will capture information only for that specific thread. If you want to capture information for more than one thread in your application, you must install the hook on each thread. Remember to remove the hook from each thread before the thread is destroyed.

The Application

Figure 23-2 presents the WH_KEYBOARD hook application’s user interface (UI). Table 23-2 presents the nondefault properties of the form and its controls. This application is fairly simple. There are two buttons and a text box on the form. The Hook button calls SetWindowsHookEx to install the WH_KEYBOARD hook, and the UnHook button calls UnhookWindowsHookEx to remove the hook. The textbox displays the three parameters of the hook’s filter function: Code, lParam, and wParam.

The WH_KEYBOARD hook example application screenshot

Figure 23-2. The ...

Get Subclassing and Hooking with Visual Basic now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.