[Winform]通过钩子监控键盘操作和鼠标移动
摘要
有这样一个需求,在程序隐藏之后,需要监控当前电脑是否有操作,如果1分钟内,无操作,则弹出视频,循环播放。
解决办法
从网上找的一个解决办法,可以通过钩子的方式实现,这里记录一下。
/// <summary>
///监控键盘钩子
/// </summary>
public class KeyboardHook
{
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105; //全局事件
public event KeyEventHandler OnKeyDownEvent;
public event KeyEventHandler OnKeyUpEvent;
public event KeyPressEventHandler OnKeyPressEvent; static int hKeyboardHook = ; //鼠标常量
public const int WH_KEYBOARD_LL = ; public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam); //声明键盘钩子事件类型
HookProc KeyboardHookProcedure; /// <summary>
/// 声明键盘钩子的封送结构类型
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode;//表示一个1到254间的虚拟键盘码
public int scanCode;//表示硬件扫描码
public int flags;
public int time;
public int dwExtraInfo;
}
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName); //安装钩子
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
//下一个钩子
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
//卸载钩子
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook); private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if ((nCode >= ) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))
{
KeyboardHookStruct MyKBHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //引发OnKeyDownEvent
if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKBHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
OnKeyDownEvent(this, e);
}
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
} public void Start()
{
if (hKeyboardHook == )
{
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(curModule.ModuleName), ); if (hKeyboardHook == )
{
Stop();
throw new Exception("Set GlobalKeyboardHook failed!");
}
}
} public void Stop()
{
bool retKeyboard = true;
if (hKeyboardHook != )
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = ;
}
if (!retKeyboard)
throw new Exception("Unload GlobalKeyboardHook failed!");
} //构造函数中安装钩子
public KeyboardHook()
{
}
//析构函数中卸载钩子
~KeyboardHook()
{
Stop();
}
}
/// <summary>
/// 监控鼠标钩子
/// </summary>
public class MouseHook
{
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; //全局的事件
public event MouseEventHandler OnMouseActivity; static int hMouseHook = ; //鼠标钩子句柄 //鼠标常量
public const int WH_MOUSE_LL = ; //mouse hook constant HookProc MouseHookProcedure; //声明鼠标钩子事件类型. //声明一个Point的封送类型
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
} //声明鼠标钩子的封送结构类型
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hWnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
//装置钩子的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); //卸下钩子的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook); //下一个钩挂的函数
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam); public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam); /// <summary>
/// 墨认的构造函数构造当前类的实例.
/// </summary>
public MouseHook()
{
} //析构函数.
~MouseHook()
{
Stop();
} public void Start()
{
//安装鼠标钩子
if (hMouseHook == )
{
//生成一个HookProc的实例.
MouseHookProcedure = new HookProc(MouseHookProc);
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, GetModuleHandle(curModule.ModuleName), ); //如果装置失败停止钩子
if (hMouseHook == )
{
Stop();
throw new Exception("SetWindowsHookEx failed.");
}
}
} public void Stop()
{
bool retMouse = true;
if (hMouseHook != )
{
retMouse = UnhookWindowsHookEx(hMouseHook);
hMouseHook = ;
} //如果卸下钩子失败
if (!(retMouse)) throw new Exception("UnhookWindowsHookEx failed.");
} private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//如果正常运行并且用户要监听鼠标的消息
if ((nCode >= ) && (OnMouseActivity != null))
{
MouseButtons button = MouseButtons.None;
int clickCount = ; switch (wParam)
{
case WM_LBUTTONDOWN:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_LBUTTONUP:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
clickCount = ;
break;
case WM_RBUTTONDOWN:
button = MouseButtons.Right;
clickCount = ;
break;
case WM_RBUTTONUP:
button = MouseButtons.Right;
clickCount = ;
break;
case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
clickCount = ;
break;
} //从回调函数中得到鼠标的信息
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
MouseEventArgs e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, ); OnMouseActivity(this, e);
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
}
使用
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
KeyboardHook key = new KeyboardHook();
MouseHook mouse = new MouseHook();
private void Form1_Load(object sender, EventArgs e)
{
mouse.OnMouseActivity += mouse_OnMouseActivity;
key.OnKeyDownEvent += key_OnKeyDownEvent;
mouse.Start();
key.Start();
this.FormClosing += Form1_FormClosing; } void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
key.Stop();
mouse.Stop();
}
void key_OnKeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e)
{
this.Text = e.KeyData.ToString();
} void mouse_OnMouseActivity(object sender, System.Windows.Forms.MouseEventArgs e)
{ this.Text = "X=" + e.X + ",Y=" + e.Y;
}
}
测试
最小化到任务栏之后
原文
http://blog.csdn.net/gdjlc/article/details/8660191
[Winform]通过钩子监控键盘操作和鼠标移动的更多相关文章
- winform窗体绑定监控键盘事件
直接注册是触发不了的, 例如: 总是不能触发. 需要在窗体设置一直属性: 大概意思是在无论窗体的那个子元素获得焦点,都将触发监控键盘的事件.
- 【Selenium02篇】python+selenium实现Web自动化:鼠标操作和键盘操作!
一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第二篇博 ...
- [转载]从MyEclipse到IntelliJ IDEA-让你摆脱鼠标,全键盘操作
从MyEclipse转战到IntelliJ IDEA的经历 注转载址:http://blog.csdn.net/luoweifu/article/details/13985835 我一个朋友写了一篇“ ...
- MFC--响应鼠标和键盘操作
一个程序最重要的部分之一是对鼠标和键盘操作的响应. 一. 理解鼠标事件.之前对鼠标事件的认识仅仅局限于处理控件的单击与双击事件.但实际鼠标的操作包含很多.这里将以一个画图的小程序讲解对鼠标的响应. ...
- Python模拟键盘输入和鼠标操作
Python模拟键盘输入和鼠标操作 一.Python键盘输入模拟: import win32api import win32con win32api.keybd_event(17,0,0,0) #c ...
- Java+selenium之WebDriver模拟鼠标键盘操作(六)
org.openqa.selenium.interactions.Actions类,主要定义了一些模拟用户的鼠标mouse,键盘keyboard操作.对于这些操作,使用 perform()方法进行执行 ...
- selenium webdriver模拟鼠标键盘操作
在测试使用Selenium webdriver测试WEB系统的时候,用到了模拟鼠标.键盘的一些输入操作. 1.鼠标的左键点击.双击.拖拽.右键点击等: 2.键盘的回车.回退.空格.ctrl.alt.s ...
- Python模拟鼠标和键盘操作实现重复性操作
前言 由于工作需要,要利用某软件去采集数据,做重复的动作大概500多次.所以想写一个程序代替人,去点击和输入. 一开始的思路有两个:1.用Python或者windows对此软件直接操作.2.利用Pyt ...
- WebDriver API——鼠标及键盘操作Actions
在自动化中我们可能需要用到鼠标或者是键盘操作,在webdriver中是Actions类进行这些操作的. 代码如下: Actions action = new Actions(driver); //-- ...
随机推荐
- 搭建RabbitMQ集群(通用)
RabbitMQ在Erlang node(节点)上 Erlang天生具有集群特性,非常好搭建集群,每一个节点(node)上具有一个叫erlang.Cookie的东西,也是一个标识符,可以互认. 1). ...
- mysql high availability 概述
一.什么是高可用性 1.可用性是指服务不间断运转的时间,通常用百分比来表示,例如 99.999%表示每年最多允许5分钟的宕机时间 2.可用性的效果和开销比例呈线性增长 3.可用性的意义往往也不尽相同, ...
- 高通Trustzone and QSEE介绍
http://blog.csdn.net/iamliuyanlei/article/details/52625968
- HTML播放FLASH(SWF)神器-SWFObject
环境 必须有 swfobject.js和 expressInstall.swf js: http://pan.baidu.com/share/link?shareid=2536087943& ...
- tensorflow variable的保存和修改(加载一部分variable到新的model中)
link: https://www.tensorflow.org/guide/saved_model 中文博客:https://blog.csdn.net/Searching_Bird/article ...
- postman发送json请求,使用案例
介绍: postman是一个很好的http模拟器,,可以发送get.post.put等各种请求,是测试服务接口相当好的工具. postman发送json请求,使用案例 发送json的具体步骤: 1. ...
- findHomography和perspectiveTransform
opencv中的两个函数,之前一直不明白这俩函数到底是要干嘛的. 得到两帧图像中的特征点后,就可以用findHomography得到单应性矩阵. 得到单应性矩阵后,可以 (1)根据相应的计算方法,由前 ...
- 移动端调试利器之vconsole
说明 由于移动端项目在手机中调试时不能使用chrome的控制台,而vconsole是对pc端console的改写 使用方法 使用 npm 安装: npm install vconsole 使用webp ...
- NFS基础配置
需要安装的包: rpc-bind nfs-utils 修改配置文件 /etc/exports 配置 /tmp *(ro) 修改配置之后记得重启服务 sudo systemctl restart nfs ...
- nodejs查询数据库后,获取result结果集并赋值返回
nodejs获取了查询结果,但不能返回出去, 情形如下: var query = function (path,id,param,sqlWhere,res){ var aa = 111;var sql ...