C#键盘hook技术
using System;using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace hook
{
public partial class Form1 : Form
{
//定义句柄变量
int hwnd = 0;
//声明MouseProc委托并定义hookCallback变量
public delegate int MouseProc(int nCode, int wParam, int lParam);
private MouseProc hookCallback = null;
//声明win32函数
[DllImport("user32.dll", EntryPoint = "CallNextHookEx")]
public static extern int CallNextHookEx(int hHook, int ncode, int Wparam, int lParam);
[DllImport("user32.dll", EntryPoint = "SetWindowsHookExA")]
public static extern int SetWindowsHookExA(int idHook, MouseProc lpfn, int hmod, int dwTreadId);
[DllImport("user32.dll", EntryPoint = "UnhookWindowsHookEx")]
public static extern int UnhookWindowsHookEx(int hHook);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int GetModuleHandle(string lpModuleName);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//实例化委托
this.hookCallback = new MouseProc(HookCallback);
//获取当前程序句柄
Process curProcess = Process.GetCurrentProcess();
ProcessModule curModule = curProcess.MainModule;
//设置钩子
hwnd = SetWindowsHookExA(13, hookCallback, GetModuleHandle(curModule.ModuleName), 0);
}
private int HookCallback(int nCode, int wParam, int lParam)
{
//判断键盘是否按下
if (wParam == 256 )
{
//输出当前按下的键
MessageBox.Show(Marshal.ReadInt32((IntPtr)lParam));
}
//到下一个钩子
CallNextHookEx(hwnd, nCode, wParam, lParam);
return 0;
}
private void button2_Click(object sender, EventArgs e)
{
//释放钩子
UnhookWindowsHookEx(hwnd);
}
}
}