A System-Wide Hook Example

If you installed the WH_MOUSE hook as a system-wide hook, you would need to create a Win32 DLL to house the filter function as well as the code required to install and remove the hook. This is because a system-wide hook must be placed in a DLL, and VB cannot create true Win32 DLLs. The system injects this DLL into every process. Therefore, any process can call our hook function.

The DLL contains two exported functions, InstallFilterDLL and UnInstallFilterDLL, as well as the filter function, MouseFunc. Example 13-4 shows the code added to the MainHook.h header file. The first line defines the MouseFunc filter function as type CALLBACK. The rest of the code defines the two exported functions as MAINHOOK_API. MAINHOOK_API is, in turn, defined as _ _decdlspec(dllexport).

Example 13-4. The MainHook.h Header File

#define MAINHOOK_API _  _declspec(dllexport)

  #define CCONV _stdcall
  #define NOMANGLE

/*
 * Define's and Structure used by WH_KEYBOARD_LL
 */
#define WH_MOUSE     7
#define HC_ACTION 0

typedef struct tagMOUSEHOOKSTRUCT {
    POINT   pt;
    HWND    hwnd;
    UINT    wHitTestCode;
    DWORD   dwExtraInfo;
} MOUSEHOOKSTRUCT, FAR *LPMOUSEHOOKSTRUCT, *PMOUSEHOOKSTRUCT;

// Function declarations
LRESULT CALLBACK MouseFunc (int nCode, WPARAM wParam, LPARAM lParam );


// These classes are exported from the MainHook.dll
#ifdef _  _cplusplus
extern "C" {
#endif 
MAINHOOK_API int InstallFilterDLL(void);
MAINHOOK_API int UnInstallFilterDLL(void);
#ifdef _  _cplusplus
}
#endif

Example 13-5 shows 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.