ÄÚÈÝ·¢²¼¸üÐÂʱ¼ä : 2026/4/19 20:13:35ÐÇÆÚÒ» ÏÂÃæÊÇÎÄÕµÄÈ«²¿ÄÚÈÝÇëÈÏÕæÔĶÁ¡£
Èí¼þʵÏÖ¼àÌý¼üÅÌʼþ
using System;
using System.Collections.Generic; using System.Text;
using System.Runtime.InteropServices; using System.Windows.Forms; using System.Reflection;
class KeyboardHook {
public event KeyEventHandler KeyDownEvent; public event KeyPressEventHandler KeyPressEvent; public event KeyEventHandler KeyUpEvent;
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam); static int hKeyboardHook = 0; //ÉùÃ÷¼üÅ̹³×Ó´¦ÀíµÄ³õʼֵ //ÖµÔÚMicrosoft SDKµÄWinuser.hÀï²éѯ
public const int WH_KEYBOARD_LL = 13; //Ï̼߳üÅ̹³×Ó¼àÌýÊó±êÏûÏ¢ÉèΪ2£¬È«¾Ö¼üÅ̼àÌýÊó±êÏûÏ¢ÉèΪ13
HookProc KeyboardHookProcedure; //ÉùÃ÷KeyboardHookProcedure×÷ΪHookProcÀàÐÍ //¼üÅ̽ṹ
[StructLayout(LayoutKind.Sequential)] public class KeyboardHookStruct {
public int vkCode; //¶¨Ò»¸öÐéÄâ¼üÂë¡£¸Ã´úÂë±ØÐëÓÐÒ»¸ö¼ÛÖµµÄ·¶Î§1ÖÁ254 public int scanCode; // Ö¸¶¨µÄÓ²¼þɨÃèÂëµÄ¹Ø¼ü public int flags; // ¼ü±êÖ¾
public int time; // Ö¸¶¨µÄʱ¼ä´Á¼ÇµÄÕâ¸öѶϢ public int dwExtraInfo; // Ö¸¶¨¶îÍâÐÅÏ¢Ïà¹ØµÄÐÅÏ¢ }
//ʹÓô˹¦ÄÜ£¬°²×°ÁËÒ»¸ö¹³×Ó
[DllImport(\CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
//µ÷Óô˺¯ÊýÐ¶ÔØ¹³×Ó
[DllImport(\CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
//ʹÓô˹¦ÄÜ£¬Í¨¹ýÐÅÏ¢¹³×Ó¼ÌÐøÏÂÒ»¸ö¹³×Ó
[DllImport(\CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
// È¡µÃµ±Ç°Ï̱߳àºÅ£¨Ï̹߳³×ÓÐèÒªÓõ½£© [DllImport(\
static extern int GetCurrentThreadId();
//ʹÓÃWINDOWS APIº¯Êý´úÌæ»ñÈ¡µ±Ç°ÊµÀýµÄº¯Êý,·ÀÖ¹¹³×ÓʧЧ [DllImport(\
public static extern IntPtr GetModuleHandle(string name);
public void Start() {
// °²×°¼üÅ̹³×Ó if (hKeyboardHook == 0) {