c# 全局钩子问题
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace wa_hooktest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
internal enum HookType //枚举,钩子的类型
{
//MsgFilter = -1,
//JournalRecord = 0,
//JournalPlayback = 1,
Keyboard = 2,
//GetMessage = 3,
//CallWndProc = 4,
//CBT = 5,
//SysMsgFilter = 6,
//Mouse = 7,
//Hardware = 8,
//Debug = 9,
//Shell = 10,
//ForegroundIdle = 11,
//CallWndProcRet = 12,
KeyboardLL = 13,
//MouseLL = 14,
};
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId(); //取得当前线程编号的API
[DllImport("User32.dll")]
internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API
[DllImport("User32.dll")]
internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); //设置Hook的API
[DllImport("User32.dll")]
internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam); //取得下一个Hook的API
IntPtr _nextHookPtr; //记录Hook编号
public delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);
public IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)
{
if (code < 0)
{
return CallNextHookEx(_nextHookPtr, code, wparam, lparam);
} //返回,让后面的程序处理该消息
if (wparam.ToInt32() == 98 || wparam.ToInt32() == 66)
{//如果用户输入的是 b
this.textBox1.Text = "a";
return (IntPtr)1; //直接返回了,该消息就处理结束了
}
else
{
return IntPtr.Zero; //返回,让后面的程序处理该消息
}
//if (wparam.ToInt32() == 91)
//{
// return (IntPtr)1;
//}
//else {
// return IntPtr.Zero;
//}
}
public void SetHook()
{
if (_nextHookPtr != IntPtr.Zero) //已经勾过了
return;
//线程钩子
HookProc myhookProc = new HookProc(MyHookProc); //声明一个自己的Hook实现函数的委托对象
//_nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc, IntPtr.Zero, GetCurrentThreadId()); //加到Hook链中
//全局钩子
_nextHookPtr = SetWindowsHookEx((int