[C #] Easy hook Library

Source: Internet
Author: User
Introduction. Net does not seem to have a good hook class library, so you have to do it yourself.

Design Concept

In the past, I Just Wanted To encapsulate the hook api into a hook class, but I found that there were not many hooks, then I declare all hook types (reference: http://msdn.microsoft.com/en-us/library/ms644959%28v=vs.85%29.aspx) together with enum.

Therefore, I use the dictionary data structure, the key is the custom hooktype, the value is the self-encapsulated hook class, And a hookmanager is used to manage the dictionary and perform the register and unregister actions on the hook.

At the same time, a custom delegate is provided during register to implement the custom hookproc.

public enum HookType{    WH_MSGFILTER = -1,    WH_JOURNALRECORD = 0,    WH_JOURNALPLAYBACK = 1,    WH_KEYBOARD = 2,    WH_GETMESSAGE = 3,    WH_CALLWNDPROC = 4,    WH_CBT = 5,    WH_SYSMSGFILTER = 6,    WH_MOUSE = 7,    WH_DEBUG = 9,    WH_SHELL = 10,    WH_FOREGROUNDIDLE = 11,    WH_CALLWNDPROCRET = 12,    WH_KEYBOARD_LL = 13,    WH_MOUSE_LL = 14}

For the wh_xxxx value in hooktype, see the Declaration in winuser. h.

class _HookProc{    #region "Declare API for Hook"    [DllImport("user32.dll", CharSet = CharSet.Auto,    CallingConvention = CallingConvention.StdCall)]    static extern int SetWindowsHookEx(int idHook, _HookProcHandler lpfn,    IntPtr hInstance, int threadId);    [DllImport("user32.dll", CharSet = CharSet.Auto,    CallingConvention = CallingConvention.StdCall)]    static extern bool UnhookWindowsHookEx(int idHook);    [DllImport("user32.dll", CharSet = CharSet.Auto,    CallingConvention = CallingConvention.StdCall)]    static extern int CallNextHookEx(int idHook, int nCode,    IntPtr wParam, IntPtr lParam);    [DllImport("kernel32.dll")]    static extern int GetCurrentThreadId();    #endregion    #region "Hook Proc"    int MyHookProc(int nCode, IntPtr wParam, IntPtr lParam)    {        if (m_CustomHookProc != null)            m_CustomHookProc(nCode, wParam, lParam);        return CallNextHookEx(m_HookHandle, nCode, wParam, lParam);    }    #endregion    CustomHookProc.HookProcHandler m_CustomHookProc;    delegate int _HookProcHandler(int nCode, IntPtr wParam, IntPtr lParam);    _HookProcHandler m_KbdHookProc;    int m_HookHandle = 0;    public _HookProc(HookType a_eHookType, CustomHookProc.HookProcHandler a_pHookProc)    {        m_CustomHookProc = a_pHookProc;        m_KbdHookProc = new _HookProcHandler(MyHookProc);        m_HookHandle = SetWindowsHookEx((int)a_eHookType, m_KbdHookProc, IntPtr.Zero, GetCurrentThreadId());        if (m_HookHandle == 0)        {            throw new Exception(string.Format("Hook {0} to {1} Error:{2}", a_eHookType.ToString(), a_pHookProc.ToString(), Marshal.GetLastWin32Error()));        }    }    ~_HookProc()    {        UnhookWindowsHookEx(m_HookHandle);        Debug.WriteLine(Marshal.GetLastWin32Error());        m_HookHandle = 0;    }}

public class CustomHookProc{    private CustomHookProc(){}    public delegate void HookProcHandler(int nCode, IntPtr wParam, IntPtr lParam);}

The previous several API declarations are methods for calling Win32 API in. Net (refer to: http://msdn.microsoft.com/en-us/library/aa984739%28v=VS.71%29.aspx ).

The point is that in myhookproc, setwindowshookex will point the hook to this function, and when this function is executed, it will throw the hook information to the external customhookproc. hookprochandler delegate.

public class HookManager{    private HookManager(){}    static readonly HookManager m_instance = new HookManager();    Dictionary<HookType, _HookProc> m_hooks = new Dictionary<HookType, _HookProc>();    public static HookManager Instance    {        get { return m_instance; }    }    public void RegisterHook(HookType a_eHookType, CustomHookProc.HookProcHandler a_pHookProc)    {        if(!m_hooks.ContainsKey(a_eHookType))        {            m_hooks.Add(a_eHookType, new _HookProc(a_eHookType, a_pHookProc));        }        else        {            throw new Exception(string.Format("{0} already exist!", a_eHookType.ToString()));        }    }    public void Unregister(HookType a_eHookType)    {        m_hooks.Remove(a_eHookType);    }}

The hookmanager class is a singleton class that maintains all the hooks.

private void Form1_Load(object sender, EventArgs e){    HookManager.Instance.RegisterHook(HookType.WH_KEYBOARD, new CustomHookProc.HookProcHandler(KeyboardHookProc));    HookManager.Instance.RegisterHook(HookType.WH_MOUSE, new CustomHookProc.HookProcHandler(MouseHookProc));}void KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam){    KeyStateInfo ctrlKey = KeyboardInfo.GetKeyState(Keys.ControlKey);    KeyStateInfo altKey = KeyboardInfo.GetKeyState(Keys.Alt);    KeyStateInfo shiftKey = KeyboardInfo.GetKeyState(Keys.ShiftKey);    KeyStateInfo f8Key = KeyboardInfo.GetKeyState(Keys.F8);    if (ctrlKey.IsPressed)    {        Console.WriteLine("Ctrl Pressed!");    }    if (altKey.IsPressed)    {        Console.WriteLine("Alt Pressed!");    }    if (shiftKey.IsPressed)    {        Console.WriteLine("Shift Pressed!");    }    if (f8Key.IsPressed)    {        Console.WriteLine("F8 Pressed!");    }}void MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam){    MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));    if (nCode >= 0)    {        String strCaption = "x = " +        MyMouseHookStruct.pt.x.ToString("d") +        "  y = " +        MyMouseHookStruct.pt.y.ToString("d");        Form tempForm = Form.ActiveForm;        tempForm.Text = strCaption;    }}

After encapsulation, it is very simple to use.

Hookmanager. instance. registerhook (hooktype. wh_keyboard, new customhookproc. hookprochandler (keyboardhookproc ));
Hookmanager. instance. registerhook (hooktype. wh_mouse, new customhookproc. hookprochandler (mousehookproc ));

For example, return callnexthookex (m_hookhandle, ncode, wparam, lparam) is not required in hookproc );

You only need to process the hook you want to process.


Reference Links

Http://msdn.microsoft.com/zh-cn/magazine/cc188966 (En-US). aspx

Download Sample Files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.