内容发布更新时间 : 2025/1/24 4:18:07星期一 下面是文章的全部内容请认真阅读。
软件实现监听键盘事件
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) {