如果这个程序在10几年前,QQ刚刚兴起的时候,有了这个代码,就可实现盗号了.

当然使用钩子我们更多的是实现"全局快捷键"的需求.

比如 程序最小化隐藏后要"某快捷键"来启动它.

钩子(hook),通俗的讲,她可以捕获到你的键盘和鼠标的相关操作消息.

关于hook的相关代码网上一搜一箩筐,这是整理起来比较完善和使用最方便的.

    //Declare wrapper managed POINT class.
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
//Declare wrapper managed MouseHookStruct class.
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
//Declare wrapper managed KeyboardHookStruct class. [StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode; //Specifies a virtual-key code. The code must be a value in the range 1 to 254.
public int scanCode; // Specifies a hardware scan code for the key.
public int flags; // Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
public int time; // Specifies the time stamp for this message.
public int dwExtraInfo; // Specifies extra information associated with the message.
} public class GlobalHook
{
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
public delegate int GlobalHookProc(int nCode, Int32 wParam, IntPtr lParam);
public GlobalHook()
{
//Start();
}
~GlobalHook()
{
Stop();
}
public event MouseEventHandler OnMouseActivity;
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event KeyEventHandler KeyUp; /// <summary>
/// 定义鼠标钩子句柄.
/// </summary>
static int _hMouseHook = 0;
/// <summary>
/// 定义键盘钩子句柄
/// </summary>
static int _hKeyboardHook = 0; public int HMouseHook
{
get { return _hMouseHook; }
}
public int HKeyboardHook
{
get { return _hKeyboardHook; }
} /// <summary>
/// 鼠标钩子常量(from Microsoft SDK Winuser.h )
/// </summary>
public const int WH_MOUSE_LL = 14;
/// <summary>
/// 键盘钩子常量(from Microsoft SDK Winuser.h )
/// </summary>
public const int WH_KEYBOARD_LL = 13; /// <summary>
/// 定义鼠标处理过程的委托对象
/// </summary>
GlobalHookProc MouseHookProcedure;
/// <summary>
/// 键盘处理过程的委托对象
/// </summary>
GlobalHookProc KeyboardHookProcedure; //导入window 钩子扩展方法导入 /// <summary>
/// 安装钩子方法
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, GlobalHookProc lpfn,IntPtr hInstance, int threadId); /// <summary>
/// 卸载钩子方法
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook); //Import for CallNextHookEx.
/// <summary>
/// 使用这个函数钩信息传递给链中的下一个钩子过程。
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam); public bool Start()
{
// install Mouse hook
if (_hMouseHook == 0)
{
// Create an instance of HookProc.
MouseHookProcedure = new GlobalHookProc(MouseHookProc);
try
{
_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
}
catch (Exception err)
{ }
//如果安装鼠标钩子失败
if (_hMouseHook == 0)
{
Stop();
return false;
//throw new Exception("SetWindowsHookEx failed.");
}
}
//安装键盘钩子
if (_hKeyboardHook == 0)
{
KeyboardHookProcedure = new GlobalHookProc(KeyboardHookProc);
try
{
_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
}
catch (Exception err2)
{ }
//如果安装键盘钩子失败
if (_hKeyboardHook == 0)
{
Stop();
return false;
//throw new Exception("SetWindowsHookEx ist failed.");
}
}
return true;
} public void Stop()
{
bool retMouse = true;
bool retKeyboard = true;
if (_hMouseHook != 0)
{
retMouse = UnhookWindowsHookEx(_hMouseHook);
_hMouseHook = 0;
}
if (_hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(_hKeyboardHook);
_hKeyboardHook = 0;
}
//If UnhookWindowsHookEx fails.
if (!(retMouse && retKeyboard))
{
//throw new Exception("UnhookWindowsHookEx ist failed.");
} }
/// <summary>
/// 卸载hook,如果进程强制结束,记录上次钩子id,并把根据钩子id来卸载它
/// </summary>
public void Stop(int hMouseHook, int hKeyboardHook)
{
if (hMouseHook != 0)
{
UnhookWindowsHookEx(hMouseHook);
}
if (hKeyboardHook != 0)
{
UnhookWindowsHookEx(hKeyboardHook);
}
} private const int WM_MOUSEMOVE = 0x200; private const int WM_LBUTTONDOWN = 0x201; private const int WM_RBUTTONDOWN = 0x204; private const int WM_MBUTTONDOWN = 0x207; private const int WM_LBUTTONUP = 0x202; private const int WM_RBUTTONUP = 0x205; private const int WM_MBUTTONUP = 0x208; private const int WM_LBUTTONDBLCLK = 0x203; private const int WM_RBUTTONDBLCLK = 0x206; private const int WM_MBUTTONDBLCLK = 0x209; private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if ((nCode >= 0) && (OnMouseActivity != null))
{
MouseButtons button = MouseButtons.None;
switch (wParam)
{
case WM_LBUTTONDOWN: //左键按下
//case WM_LBUTTONUP: //右键按下
//case WM_LBUTTONDBLCLK: //同时按下
button = MouseButtons.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
break;
}
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK)
clickCount = 2;
else clickCount = 1; //Marshall the data from callback.
MouseHookStruct MyMouseHookStruct =
(MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
MyMouseHookStruct.pt.x,
MyMouseHookStruct.pt.y,
0);
OnMouseActivity(this, e);
}
return CallNextHookEx(_hMouseHook, nCode, wParam, lParam);
} //The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the keyboard layout handle. [DllImport("user32")]
public static extern int ToAscii(int uVirtKey, //[in] Specifies the virtual-key code to be translated.
int uScanCode, // [in] Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed).
byte[] lpbKeyState, // [in] Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed). The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the CAPS LOCK key is relevant. The toggle state of the NUM LOCK and SCROLL LOCK keys is ignored.
byte[] lpwTransKey, // [out] Pointer to the buffer that receives the translated character or characters.
int fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
//The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer.
[DllImport("user32")]
public static extern int GetKeyboardState(byte[] pbKeyState); private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105; private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
// it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
KeyboardHookStruct MyKeyboardHookStruct =
(KeyboardHookStruct)Marshal.PtrToStructure(lParam,
typeof(KeyboardHookStruct));
// raise KeyDown
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyDown(this, e);
}
// raise KeyPress
if (KeyPress != null && wParam == WM_KEYDOWN)
{
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags) == 1)
{
KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
KeyPress(this, e);
}
}
// raise KeyUp
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyUp(this, e);
}
}
return CallNextHookEx(_hKeyboardHook, nCode, wParam, lParam);
}
}

  

注意:
如果运行中出现SetWindowsHookEx的返回值为0,这是因为.net 调试模式的问题,具体的做法是禁用宿主进程,在 Visual Studio 中打开项目。
在“项目”菜单上单击“属性”。
单击“调试”选项卡。
清除“启用 Visual Studio 宿主进程(启用windows承载进程)”复选框 或 勾选启用非托管代码调试

使用示例:

/// <summary>
/// 声明一个hook对象
/// </summary>
GlobalHook hook; private void Form1_Load(object sender, EventArgs e)
{
btnInstallHook.Enabled = true;
btnUnInstall.Enabled = false;
//初始化钩子对象
if (hook == null)
{
hook = new GlobalHook();
hook.KeyDown += new KeyEventHandler(hook_KeyDown);
hook.KeyPress += new KeyPressEventHandler(hook_KeyPress);
hook.KeyUp += new KeyEventHandler(hook_KeyUp);
hook.OnMouseActivity += new MouseEventHandler(hook_OnMouseActivity);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (btnUnInstall.Enabled == true)
{
hook.Stop();
}
} private void btnInstallHook_Click(object sender, EventArgs e)
{
if (btnInstallHook.Enabled == true)
{
bool r = hook.Start();
if (r)
{
btnInstallHook.Enabled = false;
btnUnInstall.Enabled = true;
MessageBox.Show("安装钩子成功!");
}
else
{
MessageBox.Show("安装钩子失败!");
}
}
}
private void btnUnInstall_Click(object sender, EventArgs e)
{
if (btnUnInstall.Enabled == true)
{
hook.Stop();
btnUnInstall.Enabled = false;
btnInstallHook.Enabled = true;
MessageBox.Show("卸载钩子成功!");
}
} /// <summary>
/// 鼠标移动事件
/// </summary>
void hook_OnMouseActivity(object sender, MouseEventArgs e)
{
lbMouseState.Text = "X:" + e.X + " Y:" + e.Y;
}
/// <summary>
/// 键盘抬起
/// </summary>
void hook_KeyUp(object sender, KeyEventArgs e)
{
lbKeyState.Text = "键盘抬起, " + e.KeyData.ToString() + " 键码:" + e.KeyValue;
}
/// <summary>
/// 键盘输入
/// </summary>
void hook_KeyPress(object sender, KeyPressEventArgs e)
{ }
/// <summary>
/// 键盘按下
/// </summary>
void hook_KeyDown(object sender, KeyEventArgs e)
{
lbKeyState.Text = "键盘按下, " + e.KeyData.ToString() + " 键码:" + e.KeyValue;
}

如果想捕获鼠标按下抬起的事件,可以修改  GlobalHook 类的 MouseHookProc方法相关代码

示例代码下载

c# 使用hook来监控鼠标键盘事件的示例代码的更多相关文章

  1. Python——pyHook监听鼠标键盘事件

    pyHook包为Windows中的全局鼠标和键盘事件提供回调. 底层C库报告的信息包括事件的时间,事件发生的窗口名称,事件的值,任何键盘修饰符等. 而正常工作需要pythoncom等操作系统的API的 ...

  2. Linux 模拟 鼠标 键盘 事件

    /************************************************************************ * Linux 模拟 鼠标 键盘 事件 * 说明: ...

  3. Python - selenium_WebDriver 鼠标键盘事件

    from selenium import webdriver #引入ActionChains类 提供了鼠标的操作方法 from selenium.webdriver.common.action_cha ...

  4. Tkinter 鼠标键盘事件(一)

    一: 鼠标事件 <Button-1>                                                                     鼠标左键单击 ...

  5. Selenium4.0+Python3系列(四) - 常见元素操作(含鼠标键盘事件)

    一.写在前面 上篇文章介绍的是关于浏览器的常见操作,接下来,我们将继续分享关于元素的常见操作,建议收藏.转发! 二.元素的状态 在操作元素之前,我们需要了解元素的常见状态. 1.常见元素状态判断,傻傻 ...

  6. 由chrome剪贴板问题研究到了js模拟鼠标键盘事件

    写在前面 最近公司在搞浏览器兼容的事情,所有浏览器兼容的问题不得不一个人包了.下面来说一下今天遇到的一个问题吧 大家都知道IE下面如果要获得剪贴板里面的信息的话,代码应该如下所示 window.cli ...

  7. openGL 初试 绘制三角形 和添加鼠标键盘事件

    code: #include <gl/glut.h> #include <stdlib.h> void render(void); void keyboard(unsigned ...

  8. 自动化测试基础篇--Selenium鼠标键盘事件

    摘自https://www.cnblogs.com/sanzangTst/p/7477382.html 前面几篇文章我们学习了怎么定位元素,同时通过实例也展示了怎么切换到iframe,怎么输入用户名和 ...

  9. Javascript鼠标键盘事件

    鼠标事件click:单击dblclick:双击mousedown:鼠标按下mouseup:鼠标抬起mouseover:鼠标悬浮mouseout:鼠标离开mousemove:鼠标移动mouseenter ...

随机推荐

  1. css overflow:hidden无效解决办法

    解决方案:只需要在设定overflow:hidden层加入定位即可 position:relative;left:0px;top:0px

  2. oracle 导入数据时提示只有 DBA 才能导入由其他 DBA 导出的文件

    提示: IMP-00013: 只有 DBA 才能导入由其他 DBA 导出的文件 IMP-00000: 未成功终止导入 解决方法: 用户system用户登录然后授权 grant dba to hszx

  3. 使用maven在netbeans下构建wicket项目

    在netbeans下构建wicket项目,网上流传较多的方法是直接使用netbeans的wicket插件,这种方法虽然简单,但是依赖的wicket版本较老,更新较慢,并且很容易与其他第三方库不兼容.使 ...

  4. 一些JS周边工具

    Visual Studio JS 辅助插件 JScript Editor Extensions 功能: 1.     代码块折叠 2.     方法参数智能提示 3.     代码块Outlining ...

  5. C#语言基础01

    Console.WriteLine("hello"); Console.ReadKey();// 按一个按键继续执行 string s=Console.ReadLine();//用 ...

  6. Using NuGet without committing packages to source control(在没有把包包提交到代码管理器的情况下使用NuGet进行还原 )

    外国老用的语言就是谨慎,连场景都限定好了,其实我们经常下载到有用NuGet引用包包然而却没法编译的情况,上谷歌百度搜又没法使用准确的关键字,最多能用到的就是nuget跟packages.config, ...

  7. C/C++——C++变量的作用域与生命周期,C语言中变量的作用域和生命周期

    全局变量 作用域:全局作用域(全局变量只需在一个源文件中定义,就可以作用于所有的源文件.) 生命周期:程序运行期一直存在 引用方法:其他文件中要使用必须用extern 关键字声明要引用的全局变量. 内 ...

  8. iOS学习中的一些误区

    周二拿到offer之后,周三确定了去哪家,今天周四.今天是一个例外.中午写更新. 人到了不同的阶段,最重要的就是要更新自己的方法论.也就是说,不能穿新鞋,走老路,这样人就不会有大的突破. 下面我就分析 ...

  9. 使用Sunny-grok实现内网转发

    Sunny-grok 申请地址:http://www.ngrok.cc ngrok.cfg配置: server_addr: "server.ngrok.cc:4443" auth_ ...

  10. 解决SQL Server Always 日志增大的问题-摘自网络

    配置了Alwayson之后,因为没有只能使用完全恢复模式,不能使用简单或大容量日志模式,所以日志不断增长,不能使用改变恢复模式的方式清空日志 手动操作收缩或截断日志也无效 读了一些文章后发现,有人使用 ...