SoFunction
Updated on 2025-03-01

HOOK keyboard hook instance code based on C# implementation

This article is a HOOK instance based on C# implementation, which can be used to block system hotkeys. The program mainly implements functions such as installing hooks, passing hooks, and unloading hooks. In the pass hook:
<param name="pHookHandle"> is the handle to your own hook function. Use this handle to traverse the hook chain</param>
<param name="nCode">Simply pass the passed parameters to CallNextHookEx</param>
<param name="wParam">Simply pass the passed parameters to CallNextHookEx</param>,
Some private variables are defined in the HOOK class: keyboard hook clause handle, keyboard hook delegate instance, underlying hook variable, etc. After the hook captures the message, the message is processed.

The specific implementation HOOK code is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace Setting and blocking system hotkeys
{
  class HOOK
  {
    #region Private variables private IntPtr m_pKeyboardHook = ;/// Keyboard hook clause handle public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);/// Hook delegation statement private HookProc m_KeyboardHookProcedure;/// Keyboard hook delegate instance  public const int idHook = 13;/// The underlying hook variable  [DllImport("", CallingConvention = )]
  public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr pInstance, int threadId);/// Install the hook  [DllImport("", CallingConvention = )]/// Unload hook  public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
    /// Pass the hook    &amp;nbsp; /// <param name="pHookHandle"> is the handle to your own hook function.  Use this handle to traverse the hook chain</param>    /// <param name="nCode">Simply pass the passed parameters to CallNextHookEx</param>    /// <param name="wParam">Simply pass the passed parameters to CallNextHookEx</param>    /// &lt;param name="lParam"&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    [DllImport("", CallingConvention = )]
    public static extern int CallNextHookEx(IntPtr pHookHandle, int nCode, Int32 wParam, IntPtr lParam);
    [StructLayout()]
    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 to block the Power key    public static int pp = 0;//Return value of hotkey    public static bool isSet = false;//Whether to set the blocking hotkey, false is the blocking hotkey.    public static bool isHotkey = false;
    public static bool isInstall = false;//Whether to install the hook, true is to install    #endregion
    #region Event Statement    public event KeyEventHandler KeyDown;//Keyboard press event    public event KeyEventHandler KeyUp;//Keyboard release event    public event KeyPressEventHandler KeyPress;//Keyboard click event    #endregion
    #region method    /// &lt;summary&gt;
    /// After the hook captures the message, process the message    /// &lt;/summary&gt;
    /// <param nCode="int">Identify, whether the keyboard is operating</param>    /// <param wParam="int">Keyboard operation value</param>    /// <param lParam="IntPtr">Pointer</param>    private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)
    {
      if (nCode &gt; -1 &amp;&amp; (KeyDown != null || KeyUp != null || KeyPress != null))
      {
        KeyMSG keyboardHookStruct = (KeyMSG)(lParam, typeof(KeyMSG));//Get relevant information about the hook        KeyEventArgs e = new KeyEventArgs((Keys)());//Get phase magnetic information of KeyEventArgs event        switch (wParam)
        {
          case WM_KEYDOWN://Keyboard press          case WM_SYSKEYDOWN:
            if (KeyDown != null)//If the current event is loaded            {
              KeyDown(this, e);//Calling this event            }
            break;
          case WM_KEYUP://Release the keyboard operation          case WM_SYSKEYUP:
            if (KeyUp != null)//If the current event is loaded            {
              KeyUp(this, e);//Calling this event            }
            break;
        }
      }
      return pp;//Whether to block the current hotkey, 1 is blocked, 2 is execution    }
    #endregion
    #region Installation and Uninstall Hook    /// &lt;summary&gt;
    /// Install the hook    /// &lt;/summary&gt;
    /// <returns>Is the installation successful</returns>    public bool Start()
    {
      IntPtr pInstance = (IntPtr)4194304;//The handle of the instance where the hook is located      if (this.m_pKeyboardHook == )//If the keyboard handle is empty      {
        this.m_KeyboardHookProcedure = new HookProc(KeyboardHookProc);//Declare a managed hook        this.m_pKeyboardHook = SetWindowsHookEx(idHook, m_KeyboardHookProcedure, pInstance, 0);//Installing the hook        if (this.m_pKeyboardHook == )//If the installation fails        {
          ();//Unload hook          return false;
        }
      }
      isInstall = true;//The hook is installed      return true;
    }
    /// &lt;summary&gt;
    /// Unload hook    /// &lt;/summary&gt;
    /// <returns>Whether the uninstall is successful</returns>    public bool Stop()
    {
      if (isInstall == false)//If there is no hook installed      {
        return true;
      }
      bool result = true;
      if (this.m_pKeyboardHook != )//If hook is installed      {
        result = (UnhookWindowsHookEx(this.m_pKeyboardHook) &amp;&amp; result);//Unload hook        this.m_pKeyboardHook = ;//Clear the keyboard hook handle      }
      return result;
    }
    #endregion Public Method  }
}