using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
IntPtr CurrHook; //得到钩子句柄
[DllImport("kernel32.dll")]
public static extern int GetCurrentThreadId(); //得到线程ID
[DllImport("user32.dll")]
//--------开始装钩子HookType:钩子类型,backCall:回调委托,MyNull:当前实例句柄,ThreadId:线程ID
public static extern IntPtr SetWindowsHookEx(int HookType, KeyBackCall backCall, IntPtr MyNull, int ThreadId);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr CurrHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern void UnhookWindowsHookEx(IntPtr CurrHook);
//----回调的委托
public delegate IntPtr KeyBackCall(int nCode, IntPtr wParam, IntPtr lParam);
//--------委托事件
public IntPtr KeyBackCallEvent(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode > 0)
{
MessageBox.Show(wParam.ToString());
return CallNextHookEx(CurrHook, nCode, wParam, lParam);
}
return CallNextHookEx(CurrHook, nCode, wParam, lParam);
}
private void button1_Click(object sender, EventArgs e)
{
CurrHook = SetWindowsHookEx(2, new KeyBackCall(KeyBackCallEvent), IntPtr.Zero, GetCurrentThreadId());
}
private void button2_Click(object sender, EventArgs e)
{
UnhookWindowsHookEx(CurrHook);
}