首页 > 编程 > .NET > 正文

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

2024-07-10 13:08:03
字体:
来源:转载
供稿:网友
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





发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表