Window Hook - The following example demonstrates creating a system wide windows
The following example demonstrates creating a system wide windows
hook under Win32. The example provides both the code for the system
hook dll and an example application. The hook function that we will
create will also demonstrate advanced coding techniques such as
sharing global memory across process boundaries using memory mapped
files, sending messages from the key hook function back to the
originating application, and dynamic loading of a dll at runtime.
The example keyboard hook that we create will keep a count of the
number of keystrokes a user enters on the keyboard. Further, we will
demonstrate trapping the enter key, and passing a message back to the
application that initiated the keyboard hook each time the enter key
is pressed. Finally, we will demonstrate trapping the left arrow key
and instead of letting it through to the current application, we will
instead replace it with a right arrow keystroke. (Note: that this can
cause much confusion to a unsuspecting user).
Adding a hook to the windows system involves calling the Windows API
function SetWindowsHookEx() and passing it the type of hook you wish
to install, and address of the hook function you are installing.
System wide hook functions are required to reside in a dynamic link
library, since they must be mapped into each process on the system.
The SetWindowsHookEx() function adds your hook function into the
Windows "hook chain", returning a handle (or id) of the hook you are
installing. You will use this handle to identify your hook to windows,
and to remove your hook when you are done trapping the keyboard.
The Windows "hook chain" is a linked list of functions that Windows
uses to keep track of all the installed hooks, allowing multiple
hooks to be installed at any given time. Occasionally, Windows will
ask your hook function to call the next hook in the chain, allowing
all the hooks an opportunity to function. When we do call the next
hook in the chain, we will need to identify ourselves by passing the
handle of our hook function to the next hook.
Creating a Windows hook requires special handling under Win32, since
the dll must be mapped (on the fly) into the process space of every
application that receives keystrokes. Normally, this is not an issue,
however, when operating inside a keyhook procedure, global variables
(such as your hook handle) must be preserved while the dll is mapped
into other process spaces. Under Win16, this would not be a program,
since dlls had a single data segment that was shared across all
process mappings. Under Win32, each mapping of the dll receives its
own data segment. This means that as the dll that contains the
keyboard hook is mapped into each process that receives keystrokes,
it receives a new data segment, and new unitialized variables with it.
This is a problem, since global variables (such as your hook handle)
must be preserved across process mappings. To solve this problem, we
will take advantage of Win32's ability to memory map variables from
the system paging file.
Each time our dll is mapped into a process, the DllMain() function
in our dll will be called by windows, with a parameter flag indicating
the reason for the call. When we receive the DLL_PROCESS_ATTACH flag
(indicating our dll is getting mapped into a different process), we
will create a file mapping to the system paging file and get a pointer
to our memory mapped variables. When we receive the DLL_PROCESS_DETACH
flag (indicating our dll is getting un-mapped from a process), we will
free our file mapping of the system paging file. The variables we will
need to keep track of (and have access to from both the dll and the
application that originally loaded the keyboard hook) are placed in a
record structure called THookRec. The THookRec structure has the
following fields:
TheHookHandle : The handle (id) of the Keyboard hook that we set. We
will need access to this variable during the execution of the keyhook
function, to identify ourselves to windows when we are asked to call
the next hook in the hook chain. We will also need access to this
variable when we remove our hook. Finally, the originating application
that will receive the messages from our hook function can access this
variable to see if and when the hook is active.
TheAppWinHandle : While this variable is not used in our example dll
or application, it is a starting place for adding additional messaging
capabilities between the hook function and your application that
initiates the hook. It can also be useful for determining if the hook
is functioning while mapped into the context of the initiating
application.
TheCtrlWinHandle : This variable will hold the handle to a button
control in our initiating application. We will use this handle to send
messages from the keyboard hook function to the button control. Every
time the enter key is pressed, we will send a WM_KEYDOWN and a
WM_KEYUP message to the button and a key value of 0 (zero). We will
trap the OnKeyDown event in the button control, and keep count of the
number of times the user presses the enter key.
TheKeyCount : This variable will keep track of the total number of key
presses made by the user. Obviously our keyhook will need access to
this variable to increment its value, and the originating application
that will receive the messages from our hook function will want to
access this variable to display real time results.
The DLL contains the following functions:
MapFileMemory : Creates a system paging file mapping object and
initializes a pointer to our mapping variable of type THookRec.
UnMapFileMemory : Frees the system paging file mapping object and
mapping variable created by the MapFileMemory() function.
GetHookRecPointer : An exported function that returns a pointer to the
mapping variable created by the MapFileMemory() function. The
initiating application can both set and examine this memory block, and
effectively share memory that is used by our hook function during the
time the hook function is operating in the context of another process
space.
KeyBoardProc : The actual hook function. This function receives both
keydown, and keyup messages as well as a message from windows
indicating we should call the next hook in the windows "hook chain".
This function increments TheKeyCount field of the memory mapped
THookRec structure if the keystroke we are processing is a keyup
message. If the key being processed is the enter key, we will fire the
OnKeyDown event of the window provided in "TheCtrlWinHandle" field of
the memory mapped THookRec structure. Finally, if the left arrow key
is pressed, we will swallow the keystroke, and instead send a right
arrow key stroke to the application. Note that the following variables
and initializing code has been included in this function for your
convience. The variables have been commented out in the code (as not
to compile). To use them, simply remove the comments in the code:
IsAltPressed {Determines if the Alt key is currently down}
IsCtrlPressed {Determines if the Control key is currently down}
IsShiftPressed {Determines if the Shift key is currently down}
StartKeyBoardHook : An exported function that allows the application
to initiate installing the keyboard hook;
StopKeyBoardHook : An exported function that allows the application
to initiate removing the keyboard hook;
DllEntryPoint : The main entry point into our dll, allowing us to know
when our dll is being mapped in, and out of, different application's
address space.