最新对C#模拟键盘按键,鼠标操作产生了兴趣。特从网上收集了一些常用的API用来调用键盘,鼠标操作。

class Win32API
{
#region DLL导入

/// <summary>
/// 用于设置窗口
/// </summary>
/// <param name="hWnd"></param>
/// <param name="hWndInsertAfter"></param>
/// <param name="X"></param>
/// <param name="Y"></param>
/// <param name="cx"></param>
/// <param name="cy"></param>
/// <param name="uFlags"></param>
/// <returns></returns>
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter,
int X, int Y, int cx, int cy, int uFlags);

/// <summary>
/// 安装钩子
/// </summary>
/// <param name="idHook"></param>
/// <param name="lpfn"></param>
/// <param name="hInstance"></param>
/// <param name="threadId"></param>
/// <returns></returns>
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr SetWindowsHookEx(WH_Codes idHook, HookProc lpfn,
IntPtr pInstance, int threadId);

/// <summary>
/// 卸载钩子
/// </summary>
/// <param name="idHook"></param>
/// <returns></returns>
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);

/// <summary>
/// 传递钩子
/// </summary>
/// <param name="idHook"></param>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(IntPtr pHookHandle, int nCode,
Int32 wParam, IntPtr lParam);

/// <summary>
/// 转换当前按键信息
/// </summary>
/// <param name="uVirtKey"></param>
/// <param name="uScanCode"></param>
/// <param name="lpbKeyState"></param>
/// <param name="lpwTransKey"></param>
/// <param name="fuState"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern int ToAscii(UInt32 uVirtKey, UInt32 uScanCode,
byte[] lpbKeyState, byte[] lpwTransKey, UInt32 fuState);

/// <summary>
/// 获取按键状态
/// </summary>
/// <param name="pbKeyState"></param>
/// <returns>非0表示成功</returns>
[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte[] pbKeyState);

[DllImport("user32.dll")]
public static extern short GetKeyStates(int vKey);

/// <summary>
/// 获取当前鼠标位置
/// </summary>
/// <param name="lpPoint"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public extern static int GetCursorPos(ref POINT lpPoint);

#endregion DLL导入
}

class Hocy_Hook
{
#region 私有常量

/// <summary>
/// 按键状态数组
/// </summary>
private readonly byte[] m_KeyState = new byte[ 256 ];

private string flags;
//flag=0 正常 flag=1 监控状态 flag=2 屏蔽键盘//

#endregion 私有常量

#region 私有变量

/// <summary>
/// 鼠标钩子句柄
/// </summary>
private IntPtr m_pMouseHook = IntPtr.Zero;

/// <summary>
/// 键盘钩子句柄
/// </summary>
private IntPtr m_pKeyboardHook = IntPtr.Zero;

/// <summary>
/// 鼠标钩子委托实例
/// </summary>
/// <remarks>
/// 不要试图省略此变量,否则将会导致
/// 激活 CallbackOnCollectedDelegate 托管调试助手 (MDA)。
/// 详细请参见MSDN中关于 CallbackOnCollectedDelegate 的描述
/// </remarks>
private HookProc m_MouseHookProcedure;

/// <summary>
/// 键盘钩子委托实例
/// </summary>
/// <remarks>
/// 不要试图省略此变量,否则将会导致
/// 激活 CallbackOnCollectedDelegate 托管调试助手 (MDA)。
/// 详细请参见MSDN中关于 CallbackOnCollectedDelegate 的描述
/// </remarks>
private HookProc m_KeyboardHookProcedure;

// 添加
public event MouseEventHandler OnMouseActivity;
private const byte VK_SHIFT = 0x10 ;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;

#endregion 私有变量

#region 事件定义

/// <summary>
/// 鼠标更新事件
/// </summary>
/// <remarks>当鼠标移动或者滚轮滚动时触发</remarks>
public event MouseUpdateEventHandler OnMouseUpdate;

/// <summary>
/// 按键按下事件
/// </summary>
public event KeyEventHandler OnKeyDown;

/// <summary>
/// 按键按下并释放事件
/// </summary>
public event KeyPressEventHandler OnKeyPress;

/// <summary>
/// 按键释放事件
/// </summary>
public event KeyEventHandler OnKeyUp;

#endregion 事件定义

#region 私有方法

/// <summary>
/// 鼠标钩子处理函数
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
private int MouseHookProc( int nCode, Int32 wParam, IntPtr lParam )
{
/*if ( ( nCode >= 0 ) && ( this.OnMouseUpdate != null )
&& ( wParam == ( int )WM_MOUSE.WM_MOUSEMOVE || wParam == ( int )WM_MOUSE.WM_MOUSEWHEEL ) )
{
MouseHookStruct MouseInfo = ( MouseHookStruct )Marshal.PtrToStructure( lParam, typeof( MouseHookStruct ) );
this.OnMouseUpdate( MouseInfo.Point.X, MouseInfo.Point.Y );
}*/
//*
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseHookStruct mouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

//detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case (int)WM_MOUSE.WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
break;
case (int)WM_MOUSE.WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
break;
case (int)WM_MOUSE.WM_MOUSEWHEEL:
//If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
//One wheel click is defined as WHEEL_DELTA, which is 120.
//(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
mouseDelta = (short)((mouseHookStruct.MouseData>> 16) & 0xffff);
//TODO: X BUTTONS (I havent them so was unable to test)
//If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
//or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
//and the low-order word is reserved. This value can be one or more of the following values.
//Otherwise, mouseData is not used.
break;
}

//double clicks
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == (int)WM_MOUSE.WM_LBUTTONDBLCLK || wParam == (int)WM_MOUSE.WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;

//generate event
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.Point.X,
mouseHookStruct.Point.Y,
mouseDelta);
//raise it
OnMouseActivity(this, e);
}

//*

return Win32API.CallNextHookEx( this.m_pMouseHook, nCode, wParam, lParam );
}

/// <summary>
/// 键盘钩子处理函数
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
/// <remarks>此版本的键盘事件处理不是很好,还有待修正.</remarks>
private int KeyboardHookProc( int nCode, Int32 wParam, IntPtr lParam )
{

switch (flags)
{
case "2":
return 1;
break;
case "1":
break;

}
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (this.OnKeyDown != null || this.OnKeyUp!= null || this.OnKeyPress!= null))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
//raise KeyDown
if (this.OnKeyDown != null && (wParam == (int)WM_KEYBOARD.WM_KEYDOWN || wParam == (int)WM_KEYBOARD.WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.VKCode;
KeyEventArgs e = new KeyEventArgs(keyData);
this.OnKeyDown(this, e);
handled = handled || e.Handled;
}

// raise KeyPress
if (this.OnKeyPress != null && wParam == (int)WM_KEYBOARD.WM_KEYDOWN)
{
bool isDownShift, isDownCapslock;
try
{
isDownShift = ((Win32API.GetKeyStates(VK_SHIFT) & 0x80) == 0x80 ? true : false);
isDownCapslock = (Win32API.GetKeyStates(VK_CAPITAL) != 0 ? true : false);
}
catch
{
isDownCapslock = false;
isDownShift= false;
}

byte[] keyState = new byte[256];
Win32API.GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (Win32API.ToAscii(MyKeyboardHookStruct.VKCode,
MyKeyboardHookStruct.ScanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.Flags) == 1)
{
char key = (char)inBuffer[0];
if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
this.OnKeyPress(this, e);
handled = handled || e.Handled;
}
}
// raise KeyUp
if (this.OnKeyUp != null && (wParam == (int)WM_KEYBOARD.WM_KEYUP || wParam == (int)WM_KEYBOARD.WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.VKCode;
KeyEventArgs e = new KeyEventArgs(keyData);
this.OnKeyUp(this, e);
handled = handled || e.Handled;
}

}

//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return Win32API.CallNextHookEx(this.m_pKeyboardHook, nCode, wParam, lParam);
}

#endregion 私有方法

#region 公共方法

/// <summary>
/// 安装钩子
/// </summary>
/// <returns></returns>
public bool InstallHook(string flagsinfo)
{
this.flags = flagsinfo;
IntPtr pInstance = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().ManifestModule);
//pInstance = (IntPtr)4194304;
// IntPtr pInstanc2 = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly());
// Assembly.GetExecutingAssembly().GetModules()[0]
// 假如没有安装鼠标钩子
if ( this.m_pMouseHook == IntPtr.Zero )
{
this.m_MouseHookProcedure = new HookProc( this.MouseHookProc );
this.m_pMouseHook = Win32API.SetWindowsHookEx( WH_Codes.WH_MOUSE_LL,this.m_MouseHookProcedure, pInstance, 0 );
if ( this.m_pMouseHook == IntPtr.Zero )
{
this.UnInstallHook();
return false;
}
}
if ( this.m_pKeyboardHook == IntPtr.Zero )
{
this.m_KeyboardHookProcedure = new HookProc( this.KeyboardHookProc );
this.m_pKeyboardHook = Win32API.SetWindowsHookEx( WH_Codes.WH_KEYBOARD_LL, this.m_KeyboardHookProcedure, pInstance, 0 );
if ( this.m_pKeyboardHook == IntPtr.Zero )
{
this.UnInstallHook();
return false;
}
}

return true;
}

/// <summary>
/// 卸载钩子
/// </summary>
/// <returns></returns>
public bool UnInstallHook()
{
bool result = true;
if ( this.m_pMouseHook != IntPtr.Zero )
{
result = ( Win32API.UnhookWindowsHookEx( this.m_pMouseHook ) && result );
this.m_pMouseHook = IntPtr.Zero;
}
if ( this.m_pKeyboardHook != IntPtr.Zero )
{
result = ( Win32API.UnhookWindowsHookEx( this.m_pKeyboardHook ) && result );
this.m_pKeyboardHook = IntPtr.Zero;
}

return result;
}

#endregion 公共方法

#region 构造函数

/// <summary>
/// 钩子类
/// </summary>
/// <remarks>本类仅仅简单实现了 WH_KEYBOARD_LL 以及 WH_MOUSE_LL </remarks>
public Hocy_Hook()
{

Win32API.GetKeyboardState( this.m_KeyState );
}

#endregion 构造函数
}

C#键盘钩子 鼠标钩子的更多相关文章

  1. c#键盘鼠标钩子

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  2. DSAPI 键盘鼠标钩子

    通常,说到Hook键盘鼠标,总需要一大堆代码,涉及各种不明白的API.而在DSAPI中,可以说已经把勾子简化到不能再简化的地步.甚至不需要任何示例代码即会使用.那么如何实现呢? Private Wit ...

  3. C# 采用钩子捕获键盘和鼠标事件-验证是否处于无人操作状态

    原文地址:https://www.cnblogs.com/gc2013/p/4036414.html 全局抽象类定义 using System; using System.Collections.Ge ...

  4. HOOK API (一)——HOOK基础+一个鼠标钩子实例

    HOOK API (一)——HOOK基础+一个鼠标钩子实例 0x00 起因 最近在做毕业设计,有一个功能是需要实现对剪切板的监控和进程的防终止保护.原本想从内核层实现,但没有头绪.最后决定从调用层入手 ...

  5. 用Delphi实现Windows的鼠标钩子函数

    Delphi是基于PASCAL语言的Windows编程工具,功能十分强大.然而在Delphi的帮助文件中,对Windows API函数的说明沿袭了 VC 的格式,和VC一样,对很多API函数的用法没有 ...

  6. VC6 鼠标钩子 最简单样例

    Windows系统是建立在事件驱动的机制上的,说穿了就是整个系统都是通过消息的传递来实现的.而钩子是Windows系统中非常重要的系统接口,用它能够截获并处理送给其它应用程序的消息,来完毕普通应用程序 ...

  7. 全局鼠标钩子:WH_MOUSE_LL, 在【 win 10 上网本】上因为太卡,运行中丢失全局鼠标钩子

    一台几年前买的上网本,让我安装了一个 win 10,然后用来测试程序的时候, 发现 使用 SetWindowsHookEx(WH_MOUSE_LL, mouseHook, GetModuleHandl ...

  8. QT实现鼠标钩子(使用SetWindowsHookEx安装mouseProc函数)

    HHOOK mouseHook=NULL; LRESULT CALLBACK mouseProc(int nCode,WPARAM wParam,LPARAM lParam ) { if(nCode ...

  9. wordpress钩子和钩子函数

    ccc,看了很多博客,无法理解,还是自己来写吧. wordpress 在wordpress中有很多钩子,还有很多钩子函数,在什么地方用什么钩子,用什么钩子函数, 需要明白两个问题: 1:什么是钩子,钩 ...

随机推荐

  1. HTML5 直播协议之 WebSocket 和 MSE

    当前为了满足比较火热的移动 Web 端直播需求, 一系列的 HTML5 直播技术迅速的发展了起来. 常见的可用于 HTML5 的直播技术有 HLS, WebSocket 与 WebRTC. 今天我要向 ...

  2. 【AT91SAM3S】英倍特串口示例工程05-UART中,串口是怎样初始化的

    在这个示例工程的main.c文件中,进入main之后,没有发现串口功能的任何配置.直接使用了printf这个东西进行输出.将软件下载到开发板上之后,在电脑端使用串口软件,可以看板子有数据发来.说明这个 ...

  3. API接口验证

    一.前言 权限验证在开发中是经常遇到的,通常也是封装好的模块,如果我们是使用者,通常指需要一个标记特性或者配置一下就可以完成,但实际里面还是有许多东西值得我们去探究.有时候我们也会用一些开源的权限验证 ...

  4. ORM框架

    半自动:iBATIS是一个半自动化的ORM框架,需要通过配置方式指定映射SQL语句 全自:由框架本身生成(如Hibernate自动生成对应SQL来持久化对象),即Hibernate属于全自动ORM框架 ...

  5. java web须知细节

    1.${pageContext.request.contextPath}是从这个请求路径(URL)上截取你的项目应用名的,比如你的项目名是hello,截取的结果应该就是/hello,/代表http// ...

  6. Linux ToolChain (二) --- Linker (1)链接选项 -L -rpath -rpath-link

    一.动态库的链接和链接选项-L,-rpath-link,-rpath (1). 现代连接器在处理动态库时将链接时路径(Link-time path)和运行时路径(Run-time path)分开, 用 ...

  7. C++ malloc new 的区别

    1,malloc与free是C++/C语言的标准库函数,new/delete是C++的运算符.它们都可用于申请动态内存和释放内存. malloc实现了在堆内存管理中进行按需分配的机制,但是它不提供在C ...

  8. Qlikview 的权限控制

    Qlikview报表控件/数据的权限控制,首先在“文档属性”->“打开”-> 勾选“基于访问权限的初始数据减少”, 这样打开报表的时候会提示输入用户名和密码. Qlikview 的权限控制 ...

  9. 多个 git ssh key 配置 Ubuntu os

    1.生成ssh key: ssh-keygen -t rsa -C “email@sss.com” 此时,在~/.ssh/文件夹下会有两个文件, id_rsa 和 id_rsa.pub.分别保存ssh ...

  10. 32、shiro框架入门3.授权

    一. 授权,也叫访问控制,即在应用中控制谁能访问哪些资源(如访问页面/编辑数据/页面操作等).在授权中需了解的几个关键对象:主体(Subject).资源(Resource).权限(Permission ...