C#中键盘钩子的使用(转)

发表于:2007-06-30来源:作者:点击数: 标签:
public class Win32Hook { [DllImport(kernel32)] public static extern int GetCurrentThreadId(); [DllImport( user32, CharSet=CharSet.Auto,CallingConvention=CallingConvention.S td Call)] public static extern intSet Windows HookEx( HookType idHo
public class Win32Hook
{

    [DllImport("kernel32")]
    public static extern int GetCurrentThreadId();

    [DllImport( "user32",
CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
    public static extern int  SetWindowsHookEx(
        HookType idHook,
        HOOKPROC lpfn,
        int hmod,
        int dwThreadId);

    public enum HookType
    {
        WH_KEYBOARD = 2
    }
    
public delegate int HOOKPROC(int nCode, int wParam, int    lParam);

    public void SetHook()
    {
        // set the keyboard hook
        SetWindowsHookEx(HookType.WH_KEYBOARD,
            new HOOKPROC(this.MyKeyboardProc),
            0,
            GetCurrentThreadId());
    }

    public int MyKeyboardProc(int nCode, int wParam, int lParam)
    {
        //在这里放置你的处理代码        return 0;
    }
}
使用方法
可以在Form的构造函数里放入
Win32Hook hook = new Win32Hook();
hook.SetHook();

原文转自:http://www.ltesting.net