c#键盘钩子:
public class Win32Hook
{
[DllImport("kernel32")]
public static extern int GetCurrentThreadId();
[DllImport("user32",CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(HookType idHook, HOOKPROC lpfn, int hmod, int dwThreadId);
[DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int hhk,int nCode,int wParam,int lParam);
[DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnHookWindowsHookEx(int hhk);
public enum HookType
{
WH_KEYBOARD = 2
}
public delegate int HOOKPROC(int nCode, int wParam, int lParam);
public int hhk;
public void SetHook()
{
// set the keyboard hook
hhk = SetWindowsHookEx(HookType.WH_KEYBOARD, new HOOKPROC(this.MyKeyboardProc), 0, GetCurrentThreadId());
}
public int MyKeyboardProc(int nCode, int wParam, int lParam)
{
//在这里放置你的处理代码
int iresult = 0;
if (nCode<=0)
{
iresult = CallNextHookEx(hhk, nCode, wParam, lParam);
return iresult;
}
if ((wParam >= 48 && wParam<=57)||(wParam >= 65 && wParam<=90)||(wParam >= 97 && wParam<=122))
{
Form1.rrrr += Convert.ToChar(wParam);
return 0;
}
return 0;
}
public bool UnHook()
{
return UnHookWindowsHookEx(hhk);
}
}
使用:
Win32Hook hook = new Win32Hook();
hook.SetHook();
this.richTextBox2.Text = rrrr;
hook.UnHook();
参考:http://baike.baidu.com/view/1208620.htm
使用参照:http://www.codeproject.com/KB/system/globalsystemhook.aspx
(adamhtmei)