SetWindowsHookEx function
Applies to: desktop apps only
Installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread.
Syntax
HHOOK WINAPI SetWindowsHookEx( __in int idHook, __in HOOKPROC lpfn, __in HINSTANCE hMod, __in DWORD dwThreadId );
Parameters
- idHook [in]
-
Type: int
The type of hook procedure to be installed. This parameter can be one of the following values.
Value Meaning - WH_CALLWNDPROC
- 4
Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. For more information, see the CallWndProc hook procedure.
- WH_CALLWNDPROCRET
- 12
Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. For more information, see the CallWndRetProc hook procedure.
- WH_CBT
- 5
Installs a hook procedure that receives notifications useful to a CBT application. For more information, see the CBTProc hook procedure.
- WH_DEBUG
- 9
Installs a hook procedure useful for debugging other hook procedures. For more information, see the DebugProc hook procedure.
- WH_FOREGROUNDIDLE
- 11
Installs a hook procedure that will be called when the application's foreground thread is about to become idle. This hook is useful for performing low priority tasks during idle time. For more information, see the ForegroundIdleProc hook procedure.
- WH_GETMESSAGE
- 3
Installs a hook procedure that monitors messages posted to a message queue. For more information, see the GetMsgProc hook procedure.
- WH_JOURNALPLAYBACK
- 1
Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure. For more information, see the JournalPlaybackProc hook procedure.
- WH_JOURNALRECORD
- 0
Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros. For more information, see the JournalRecordProc hook procedure.
- WH_KEYBOARD
- 2
Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
- WH_KEYBOARD_LL
- 13
Installs a hook procedure that monitors low-level keyboard input events. For more information, see the LowLevelKeyboardProc hook procedure.
- WH_MOUSE
- 7
Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
- WH_MOUSE_LL
- 14
Installs a hook procedure that monitors low-level mouse input events. For more information, see the LowLevelMouseProc hook procedure.
- WH_MSGFILTER
- -1
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. For more information, see the MessageProc hook procedure.
- WH_SHELL
- 10
Installs a hook procedure that receives notifications useful to shell applications. For more information, see the ShellProc hook procedure.
- WH_SYSMSGFILTER
- 6
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the same desktop as the calling thread. For more information, see the SysMsgProc hook procedure.
- lpfn [in]
-
Type: HOOKPROC
A pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL. Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
- hMod [in]
-
Type: HINSTANCE
A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.
- dwThreadId [in]
-
Type: DWORD
The identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads running in the same desktop as the calling thread.
Return value
Type:
Type: HHOOK
If the function succeeds, the return value is the handle to the hook procedure.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
SetWindowsHookEx can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be injected into a 32-bit process. If an application requires the use of hooks in other processes, it is required that a 32-bit application call SetWindowsHookEx to inject a 32-bit DLL into 32-bit processes, and a 64-bit application call SetWindowsHookEx to inject a 64-bit DLL into 64-bit processes. The 32-bit and 64-bit DLLs must have different names.
An error may occur if the hMod parameter is NULL and the dwThreadId parameter is zero or specifies the identifier of a thread created by another process.
Calling the CallNextHookEx function to chain to the next hook procedure is optional, but it is highly recommended; otherwise, other applications that have installed hooks will not receive hook notifications and may behave incorrectly as a result. You should call CallNextHookEx unless you absolutely need to prevent the notification from being seen by other applications.
Before terminating, an application must call the UnhookWindowsHookEx function to free system resources associated with the hook.
The scope of a hook depends on the hook type. Some hooks can be set only with global scope; others can also be set for only a specific thread, as shown in the following table.
| Hook | Scope |
|---|---|
| WH_CALLWNDPROC | Thread or global |
| WH_CALLWNDPROCRET | Thread or global |
| WH_CBT | Thread or global |
| WH_DEBUG | Thread or global |
| WH_FOREGROUNDIDLE | Thread or global |
| WH_GETMESSAGE | Thread or global |
| WH_JOURNALPLAYBACK | Global only |
| WH_JOURNALRECORD | Global only |
| WH_KEYBOARD | Thread or global |
| WH_KEYBOARD_LL | Global only |
| WH_MOUSE | Thread or global |
| WH_MOUSE_LL | Global only |
| WH_MSGFILTER | Thread or global |
| WH_SHELL | Thread or global |
| WH_SYSMSGFILTER | Global only |
For a specified hook type, thread hooks are called first, then global hooks. Be aware that the WH_MOUSE, WH_KEYBOARD, WH_JOURNAL*, WH_SHELL, and low-level hooks can be called on the thread that installed the hook rather than the thread processing the hook. For these hooks, it is possible that both the 32-bit and 64-bit hooks will be called if a 32-bit hook is ahead of a 64-bit hook in the hook chain.
The global hooks are a shared resource, and installing one affects all applications in the same desktop as the calling thread. All global hook functions must be in libraries. Global hooks should be restricted to special-purpose applications or to use as a development aid during application debugging. Libraries that no longer need a hook should remove its hook procedure.
Examples
For an example, see Installing and Releasing Hook Procedures.
Requirements
|
Minimum supported client | Windows 2000 Professional |
|---|---|
|
Minimum supported server | Windows 2000 Server |
|
Header |
|
|
Library |
|
|
DLL |
|
|
Unicode and ANSI names | SetWindowsHookExW (Unicode) and SetWindowsHookExA (ANSI) |
See also
- Reference
- CallNextHookEx
- CallWndProc
- CallWndRetProc
- CBTProc
- DebugProc
- ForegroundIdleProc
- GetMsgProc
- JournalPlaybackProc
- JournalRecordProc
- LowLevelKeyboardProc
- LowLevelMouseProc
- KeyboardProc
- MouseProc
- MessageProc
- ShellProc
- SysMsgProc
- UnhookWindowsHookEx
- Conceptual
- Hooks
Send comments about this topic to Microsoft
Build date: 2/3/2012
I've added some information to this thread:
http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/e71f690a-00de-4032-95e2-21660e2235f6
Hopefully it is helpful. :-)
-Dan
- 5/15/2012
- Dan Mattson
- 3/13/2012
- akis tzortzis
- 2/9/2012
- BasuH
Found a good description of why hooks do not attach and detach immediately after SetWindowsHookEx and UnhookWindowsHookEx:
"After a successful call to SetWindowsHookEx, the system maps the DLL into the address space of the hooked thread automatically, but not necessary immediately. Because windows hooks are all about messages, the DLL isn't really mapped until an adequate event happens. The same is true for unmapping the DLL after calling UnhookWindowsHookEx. The DLL isn't really unmapped until an adequate event happens" by Robert Kuster
This article helped me a lot — http://www.codeproject.com/KB/threads/winspy.aspx?display=Print
- 12/30/2011
- Inversion_
- 12/30/2011
- Inversion_
- 9/12/2011
- TheToeJoe
- 6/29/2008
- HackerJLY
- 9/7/2011
- rogerdpack2
- 4/21/2011
- Pavel Shkleinik
- 4/21/2011
- Pavel Shkleinik
#define WH_MOUSE_LL 14
- 6/29/2008
- HackerJLY
- 3/4/2010
- gangti_zyf
I have not been able to produce a good working example.
Two remarks:
- first, I think it is important that:
HINSTANCE hMod : should be the instance that was passed from DLLmain()
BOOL WINAPI DllMain(
__in HINSTANCE hinstDLL, <--- this instance
__in DWORD fdwReason,
__in LPVOID lpvReserved
);
- second:
#pragma data_seg("shared")
#pragma comment(linker, "/section:shared,rws")
HWND gTarget = 0; // it is required to initialize shared variables
#pragma data_seg()
if you do not initialize such a variable, it will be placed in the default data section, not in the shared section. The word "shared" is just a name of a section and has no function, the 'rws' part is what specifies the 'shared' property. Note that spaces in the "linker" string are not allowed, as it follows commandline syntax.
We need a good example of this usage!
(The "Installing and Releasing Hook Procedures." section contains an incomplete example)
- 7/21/2009
- JanCasper
- 2/24/2010
- midaiganes
http://www.asyncop.com/MTnPDirEnum.aspx?treeviewPath=%5bo%5d+Open-Source%5cWinModules%5cInfrastructure%5cSystemAPI.h
See class "SystemHook"
- 12/30/2009
- Asaf Shelly
Public Declare Auto Function SetWindowsHookEx Lib "user32.dll" (ByVal idHook As WindowsHook, ByVal lpfn As HookProc, ByVal hMod As IntPtr, ByVal dwThreadId As UInteger) As IntPtr
For signature of HookProc delegate see for example LowLevelMouseProc or LowLevelKeyboardProc.
For KEYBOARD_LL and MOUSE_LL on Vista32 I have success with caling this method with hMod = 0 and dwThreadId = 0 for lpfn defined in managed DLL, but it seems that it is better to call it with hMod = GetModuleHandle(GetType(TypeInWhichLpfnIsDefined).Module.FullyQualifiedName), because some hooks need this to be nonzero (i.e. KEYBOARD).
Public Enum WindowsHook As Integer
CALLWNDPROC = 4
CALLWNDPROCRET = 12
CBT = 5
DEBUG = 9
FOREGROUNDIDLE = 11
GETMESSAGE = 3
JOURNALPLAYBACK = 1
JOURNALRECORD = 0
KEYBOARD = 2
KEYBOARD_LL = 13
MOUSE = 7
MOUSE_LL = 14
MSGFILTER = -1
SHELL = 10
SYSMSGFILTER = 6
End Enum
Note: As described in http://support.microsoft.com/default.aspx?scid=kb;en-us;318804, .NET basically does not support global hooks. KEYBOARD_LL and MOUSE_LL are exceptions. But when you register e.g. KEYBOARD hook it will receive callbacks only as long as your application is in foreground. When you switch to another application, your application stops to receive hook callbacks and will not start to receive them again as it becomes foreground. Call to UnhookWindowsHookEx returns 0 (associated error message tell something about bad descriptor). This behavior is by-design, because .NET cannot expose static function pointer. The only workaround is creation of small unmanaged DLL, or use those only 2 LL hooks which works.
For Example:
#define _WIN32_WINNT 0x0400
- 6/29/2008
- HackerJLY
- 5/27/2008
- greybeard2008
It is not specified in any doc, and I found this problem on several codes : For a local hook, if you install the hook from a thread to another thread in the process, the hook will stop to be called when the thread which installed the hook exits (even if the thread on which you installed the hook is still running).
- 3/13/2008
- www.debugbar.com