C#.Net的全域鍵盤鉤子(Hook)技術

來源:互聯網
上載者:User

 

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace HookDll
{
 public class HookDll
 {
  private KBDLLHOOKSTRUCT kbdllhs; 
  private IntPtr iHookHandle  =IntPtr.Zero;
  private GCHandle _hookProcHandle;
  public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
  [DllImport("user32.dll", CharSet=CharSet.Auto)]
  public static extern IntPtr SetWindowsHookEx(int hookid, HookProc pfnhook, IntPtr hinst, int threadid);
  
  [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
  public static extern bool UnhookWindowsHookEx(IntPtr hhook);
 
  [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
  public static extern IntPtr CallNextHookEx(IntPtr hhook, int code, IntPtr wparam, IntPtr lparam);
  [DllImport("kernel32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
  private static extern IntPtr GetModuleHandle(string lpModuleName);
  [DllImport("Kernel32.dll",EntryPoint="RtlMoveMemory")] 
  public static extern void CopyMemory (ref KBDLLHOOKSTRUCT Source,IntPtr Destination,int Length);

  private const int WH_KEYBOARD = 13;
  
  public void DisableKBDHook()
  {
   try
   {
    if (iHookHandle!=IntPtr.Zero)
    {
     UnhookWindowsHookEx(iHookHandle);
    }
    _hookProcHandle.Free();
    iHookHandle = IntPtr.Zero;
   }
   catch
   {
    return;
   }
  }
  public void EnableKBDHook()
  { 
   HookProc hookProc = new HookProc(KBDDelegate);
   _hookProcHandle  = GCHandle.Alloc(hookProc);
   iHookHandle   = SetWindowsHookEx(WH_KEYBOARD, hookProc, GetModuleHandle("HookDll.dll"), 0);
   if (iHookHandle == IntPtr.Zero) 
   {
    throw new System.Exception("錯誤,鉤子失敗!");
   }
  }
  public IntPtr KBDDelegate(int iCode , IntPtr wParam,IntPtr lParam)
  {
   kbdllhs    = new KBDLLHOOKSTRUCT();
   CopyMemory(ref kbdllhs, lParam, 20);
   
   //結果就在這裡了^_^
   int iHookCode = kbdllhs.vkCode;
   DisableKBDHook();
   EnableKBDHook();
   return CallNextHookEx(iHookHandle, iCode, wParam,lParam);
  }
 }
 [StructLayout(LayoutKind.Sequential)]
 public struct KBDLLHOOKSTRUCT
 {
  public int vkCode;
  public int scanCode;
  public int flags;
  public int time;
  public int dwExtraInfo;
 }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.