HOOK keyboard hook instance code based on C

  • 2020-06-23 01:47:07
  • OfStack

This article describes an instance of HOOK based on an C# implementation that can be used to mask system hotkeys. The procedure mainly realizes the installation hook, the transfer hook, uninstalls the hook and so on function. In the transfer hook:
< param name="pHookHandle" > Is a handle to your own hook function. This handle allows you to traverse the hook chain < /param >
< param name="nCode" > Simply pass in the parameters to CallNextHookEx < /param >
< param name="wParam" > Simply pass the parameters to CallNextHookEx < /param > .
In the HOOK class, a number of private variables are defined: keyboard hook handles, keyboard hook delegate instances, underlying hook variables, and so on. After the hook captures the message, it is processed.

Specific implementation HOOK code is as follows:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
namespace  Set and shield system hotkeys 
{
  class HOOK
  {
    #region  Private variables 
 private IntPtr m_pKeyboardHook = IntPtr.Zero;///  Keyboard hook handle 
 public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);///  Hook delegation declaration 
 private HookProc m_KeyboardHookProcedure;///  Keyboard hook delegate instance 
  public const int idHook = 13;///  The underlying hook variable 
  [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
  public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr pInstance, int threadId);///  Install hooks 
  [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]///  Uninstall hooks 
  public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
    ///  Pass the hook 
    &nbsp; /// <param name="pHookHandle"> Is a handle to your own hook function. This handle allows you to traverse the hook chain </param>
    /// <param name="nCode"> Simply pass in the parameters CallNextHookEx Can be </param>
    /// <param name="wParam"> Simply pass in the parameters CallNextHookEx Can be </param>
    /// <param name="lParam"></param>
    /// <returns></returns>
    [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern int CallNextHookEx(IntPtr pHookHandle, int nCode, Int32 wParam, IntPtr lParam);
    [StructLayout(LayoutKind.Sequential)]
    public struct KeyMSG
    {
      public int vkCode;
      public int scanCode;
      public int flags;
      public int time;
      public int dwExtraInfo;
    }
    protected const int WM_QUERYENDSESSION = 0x0011;
    protected const int WM_KEYDOWN = 0x100;
    protected const int WM_KEYUP = 0x101;
    protected const int WM_SYSKEYDOWN = 0x104;
    protected const int WM_SYSKEYUP = 0x105;
    protected const byte VK_SHIFT = 0x10;
    protected const byte VK_CAPITAL = 0x14;
    protected const byte VK_NUMLOCK = 0x90;
    protected const byte VK_LSHIFT = 0xA0;
    protected const byte VK_RSHIFT = 0xA1;
    protected const int VK_LWIN = 91;
    protected const int VK_RWIN = 92;
    protected const byte VK_LCONTROL = 0xA2;
    protected const byte VK_RCONTROL = 0x3;
    protected const byte VK_LALT = 0xA4;
    protected const byte VK_RALT = 0xA5;
    protected const byte LLKHF_ALTDOWN = 0x20;
    public bool Porwer = true;// Whether shielding Porwer key 
    public static int pp = 0;// The return value of the hotkey 
    public static bool isSet = false;// Whether to set the shield hotkey ,false The hotkey for setting the shield 
    public static bool isHotkey = false;
    public static bool isInstall = false;// Whether to install hooks, true To install 
    #endregion
    #region  Statement of events 
    public event KeyEventHandler KeyDown;// Keyboard press event 
    public event KeyEventHandler KeyUp;// Keyboard release event 
    public event KeyPressEventHandler KeyPress;// Keyboard click event 
    #endregion
    #region  methods 
    /// <summary>
    ///  After the hook captures the message, it processes it 
    /// </summary>
    /// <param nCode="int"> Identifies whether the keyboard operates </param> 
    /// <param wParam="int"> The operation value of the keyboard </param>
    /// <param lParam="IntPtr"> Pointer to the </param>
    private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)
    {
      if (nCode > -1 && (KeyDown != null || KeyUp != null || KeyPress != null))
      {
        KeyMSG keyboardHookStruct = (KeyMSG)Marshal.PtrToStructure(lParam, typeof(KeyMSG));// Gets information about hooks 
        KeyEventArgs e = new KeyEventArgs((Keys)(keyboardHookStruct.vkCode));// To obtain KeyEventArgs Phase magnetic information of events 
        switch (wParam)
        {
          case WM_KEYDOWN:// Keyboard press operation 
          case WM_SYSKEYDOWN:
            if (KeyDown != null)// If the current event is loaded 
            {
              KeyDown(this, e);// Calling this event 
            }
            break;
          case WM_KEYUP:// Keyboard release operation 
          case WM_SYSKEYUP:
            if (KeyUp != null)// If the current event is loaded 
            {
              KeyUp(this, e);// Calling this event 
            }
            break;
        }
      }
      return pp;// Whether to screen the current hotkey, 1 As the block, 2 To carry out 
    }
    #endregion
    #region  Install and uninstall hooks 
    /// <summary>
    ///  Install hooks 
    /// </summary>
    /// <returns> Whether the installation is successful </returns>
    public bool Start()
    {
      IntPtr pInstance = (IntPtr)4194304;// Handle to the instance where the hook is located 
      if (this.m_pKeyboardHook == IntPtr.Zero)// If the keyboard handle is empty 
      {
        this.m_KeyboardHookProcedure = new HookProc(KeyboardHookProc);// The statement 1 A managed hook 
        this.m_pKeyboardHook = SetWindowsHookEx(idHook, m_KeyboardHookProcedure, pInstance, 0);// Install hooks 
        if (this.m_pKeyboardHook == IntPtr.Zero)// If the installation fails 
        {
          this.Stop();// Uninstall hooks 
          return false;
        }
      }
      isInstall = true;// Hooks are installed 
      return true;
    }
    /// <summary>
    ///  Uninstall hooks 
    /// </summary>
    /// <returns> Whether the unloading is successful </returns>
    public bool Stop()
    {
      if (isInstall == false)// If no hooks are installed 
      {
        return true;
      }
      bool result = true;
      if (this.m_pKeyboardHook != IntPtr.Zero)// If hooks are installed 
      {
        result = (UnhookWindowsHookEx(this.m_pKeyboardHook) && result);// Uninstall hooks 
        this.m_pKeyboardHook = IntPtr.Zero;// Clear the hook handle of the keyboard 
      }
      return result;
    }
    #endregion  Public methods 
  }
}

Related articles: