HOW TO: Set a Windows Hook in Visual C# .NET
Article ID | : | 318804 |
Last Review | : | February 10, 2003 |
Revision | : | 2.0 |
This article was previously published under Q318804
On this Page
![]() | SUMMARY | |
![]() | REFERENCES |
SUMMARY
This article describes how to set a hook that is specific to a thread and to a hook procedure by using the mouse hook as an example. You can use hooks to monitor certain types of events. You can associate these events with a specific thread or with all of the threads in the same desktop as a calling thread.
back to the top
To set a mouse hook and to monitor the mouse events, follow these steps:
back to the top
back to the top
back to the top
Set a Mouse Hook
To set a hook, call the SetWindowsHookEx function from the User32.dll file. This function installs an application-defined hook procedure in the hook chain that is associated with the hook.To set a mouse hook and to monitor the mouse events, follow these steps:
1. | Start Microsoft Visual Studio .NET. |
2. | On the File menu, point to New, and then click Project. |
3. | In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates. In the Name box, type ThreadSpecificMouseHook. Form1 is added to the project by default. |
4. | Add the following line of code in the Form1.cs file after the other using statements:
|
5. | Add following code in the Form1 class:
|
6. | Add a Button control to the form, and then add the following code in the Button1_click procedure:
|
7. | Add the following code for the MouseHookProc function in the Form1 class:
|
8. | Press F5 to run the project, and then click the button on the form to set the hook. The mouse coordinates appear on the form caption bar when the pointer moves on the form. Click the button again to remove the hook. |
Global Hook Is Not Supported in .NET Framework
You cannot implement global hooks in Microsoft .NET Framework. To install a global hook, a hook must have a native dynamic-link library (DLL) export to inject itself in another process that requires a valid, consistent function to call into. This requires a DLL export, which .NET Framework does not support. Managed code has no concept of a consistent value for a function pointer because these function pointers are proxies that are built dynamically.back to the top
REFERENCES
For more information about windows hooks, see the following MSDN documentation:
back to the top