HOW TO: Set a Windows Hook in Visual C# .NET

HOW TO: Set a Windows Hook in Visual C# .NET
The information in this article applies to:
Microsoft .NET Framework SDK
Microsoft Visual C# .NET (2002)

IN THIS TASK
SUMMARY
Set a Mouse Hook
Global Hook Is Not Supported in .NET Framework
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

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:
Start Microsoft Visual Studio .NET.
On the File menu, point to New, and then click Project.
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.
Add the following line of code in the Form1.cs file after the other using statements:
using System.Runtime.InteropServices;
Add following code in the Form1 class:
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

//Declare hook handle as int.
static int hHook = 0;

//Declare mouse hook constant.
//For other hook types, you can obtain these values from Winuser.h in Microsoft SDK.
public const int WH_MOUSE = 7;
private System.Windows.Forms.Button button1;

//Declare MouseHookProcedure as HookProc type.
HookProc MouseHookProcedure;            

//Declare wrapper managed POINT class.
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
    public int x;
    public int y;
}

//Declare wrapper managed MouseHookStruct class.
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
    public POINT pt;
    public int hwnd;
    public int wHitTestCode;
    public int dwExtraInfo;
}

//Import for SetWindowsHookEx function.
//Use this function to install thread-specific hook.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
IntPtr hInstance, int threadId);

//Import for UnhookWindowsHookEx.
//Call this function to uninstall the hook.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
        
//Import for CallNextHookEx.
//Use this function to pass the hook information to next hook procedure in chain.
[DllImport("user32.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode,
IntPtr wParam, IntPtr lParam);  
Add a Button control to the form, and then add the following code in the Button1_click procedure:
private void button1_Click(object sender, System.EventArgs e)
{
    if(hHook == 0)
    {
            // Create an instance of HookProc.
        MouseHookProcedure = new HookProc(Form1.MouseHookProc);
                
        hHook = SetWindowsHookEx(WH_MOUSE,
                    MouseHookProcedure,
                    (IntPtr)0,
                    AppDomain.GetCurrentThreadId());
        //If SetWindowsHookEx fails.
        if(hHook == 0 )
        {
            MessageBox.Show("SetWindowsHookEx Failed");
            return;
        }
        button1.Text = "UnHook Windows Hook";
    }
    else
    {
        bool ret = UnhookWindowsHookEx(hHook);
        //If UnhookWindowsHookEx fails.
        if(ret == false )
        {
            MessageBox.Show("UnhookWindowsHookEx Failed");
            return;
        }
        hHook = 0;
        button1.Text = "Set Windows Hook";
        this.Text = "Mouse Hook";
    }
}
Add the following code for the MouseHookProc function in the Form1 class:
public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    //Marshall the data from callback.
    MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    if (nCode < 0)
    {
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    }
    else
    {
        //Create a string variable with shows current mouse. coordinates
        String strCaption = "x = " +
                MyMouseHookStruct.pt.x.ToString("d") +
                    "  y = " +
        MyMouseHookStruct.pt.y.ToString("d");
        //Need to get the active form because it is a static function.
        Form tempForm = Form.ActiveForm;
        
        //Set the caption of the form.
        tempForm.Text = strCaption;
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    }
}
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.
back to the top
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:
About Hooks
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/hooks_9rg3.asp
back to the top

时间: 2024-10-03 17:46:08

HOW TO: Set a Windows Hook in Visual C# .NET的相关文章

HOW TO: Set a Windows Hook in Visual C# .NET-Windo

HOW TO: Set a Windows Hook in Visual C# .NETThe information in this article applies to:Microsoft .NET Framework SDKMicrosoft Visual C# .NET (2002)IN THIS TASKSUMMARYSet a Mouse HookGlobal Hook Is Not Supported in .NET FrameworkREFERENCESSUMMARYThis a

[原创]一个简单的windows HOOK - 隐藏进程管理器中特定的进程

一个简单的windows HOOK - 隐藏进程管理器中特定的进程  (适用平台:windows 2000 sp4,windows XP sp2)           屏蔽任务管理器中的进程名称有很多种方法,可以在ring0级做文章: 修改内核进程链表,拦截内核API等.我这里只给出win32下的实现,原 理是最普通的 windows 钩子机制.实现语言 win32 汇编 (masm32):   0 在DllEntry中处理资源取得和产生"工作"线程: mov eax,_hinstan

学生信息系统求助-有没有用vs2010加access 2003,Windows forms application Visual C#做学生信息系统的资料,

问题描述 有没有用vs2010加access 2003,Windows forms application Visual C#做学生信息系统的资料, 期末大作业有点棘手啊,老师讲的天花乱坠而我却难以下手 解决方案 http://download.csdn.net/detail/fg201041842103/6021349

在 Windows 上使用 Visual Studio 编译 CURL

导语: 教你科学地编译 Windows 版本的 libcurl (使用Windows SSPI或者OpenSSL) 准备工具 CMake (3.4.0) Zlib (1.2.8) libcurl (7.45.0) OpenSSL (1.0.2d) Visual Studio 2015 目标 得到可以使用的 libcurl 静态库 步骤 编译Zlib 打开CMake,把 Zlib 目录下的 CMakeList.txt 拖进去,生成解决方案,这一步不能用 contrib\vstudio 下的 sln

Windows下用Visual Studio来build ImageMagick

参考: http://www.imagemagick.org/script/install-source.php#windows http://blog.163.com/anteaus_20/blog/static/24422224200811924810941/   [Build过程] 1)根据ImageMagick在Windows下的安装指南,在这里下载源码包(以6.8.9为例),解压,进入解压后的目录. 2)在Visual Studio(以VS2008为例)中,打开 ImageMagick

Windows XP与Visual Studio 2010的结合

VS2010已经发布了正式版,在这个新的工具中,有很多地方可以与XP结合. XP(Extreme Programming)是极限编程,是敏捷编程中的一种. 极限编程中的思路是: 计划游戏,小版本,隐喻,简单设计,测试,重构,结对编程,集体所有权,持续集成,每 周工作40小时,现场客户,编码标准. 在极限编程中,强调的是人,强调的是灵活.然而极限编程中在VSTS中能有怎样的结合呢? 在这里,我只想说说我浅薄的想法. 在极限编程中的这些思路中,并不是所有的思路点都能在VSTS中得以实现的,这里,我只

用Visual C#创建Windows服务程序

visual|window|程序|创建  一.Windows服务介绍: Windows服务以前被称作NT服务,是一些运行在Windows NT.Windows 2000和Windows XP等操作系统下用户环境以外的程序.在以前,编写Windows服务程序需要程序员很强的C或C++功底.然而现在在Visual Studio.Net下,你可以运用C++或Visual C#或Visual Basic.Net很轻松的创建一个Windows服务程序.同样,你还可以运用其他任何与CLR相容的语言来创建Wi

Windows Azure革新:欢迎来到Visual Studio 2012

当微软发布第一个预览版的Windows 8和Visual Studio,社区里很多人在问,windows azure tool是否可用?答案是"否".微软承诺windows azure tool(目前)只支持http://www.aliyun.com/zixun/aggregation/13385.html">Visual Studio 2010,只有2012版最终发布了,windows azure tool将可用.现在,随着新版本的windows azure平台的发布

WPF : 自定义Windows Presentation Foundation的控件

虽然 Windows Presentation Foundation 中的控件模型非常多,但仍不可能提供需要的每一种控件.这时候,控件编写就派上用场了.在本文中,我将向您讲述如何使用 Windows Presentation Foundation 自定义现有控件,以及如何为您的项目创建全新的控件(或元素). 在开发一个自定义控件之前,应该先问问自己是否真的需要它.在 Windows Presentation Foundation 中,组合.样式和模板化功能使您可以自定义现有控件,这是以前的技术所