c#全局鼠标事件以及鼠标事件模拟
最近在编写Max插件时,其主容器FlowLayoutPanel由于隐藏了滚动条,要实现按住鼠标中键上下拖动的功能,因此尝试了全局鼠标事件、以及鼠标勾子,可惜由于Max不争气?都未能实现,于是代码报废,故将其分享于此。
一、全局鼠标事件,首先构建鼠标事件处理器
public delegate void MouseMovedEvent();
public delegate void MouseMDownEvent();
public delegate void MouseMUpEvent();
public class GlobalMouseHandler : IMessageFilter
{
private const int WM_MOUSEMOVE = 0x0200;
private const int WM_MBUTTONDOWN = 0x0207;
private const int WM_MBUTTONUP = 0x0208;
public event MouseMovedEvent TheMouseMoved;
public event MouseMDownEvent TheMouseMDown;
public event MouseMUpEvent TheMouseMUp;
#region IMessageFilter Members
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_MOUSEMOVE)
if (TheMouseMoved != null)
TheMouseMoved();
if (m.Msg == WM_MBUTTONDOWN)
if (TheMouseMDown != null)
TheMouseMDown();
if (m.Msg == WM_MBUTTONUP)
if (TheMouseMUp != null)
TheMouseMUp();
// Always allow message to continue to the next filter control
return false;
}
#endregion
}
然后在FlowLayoutPanel的构造函数中添加如下代码(其事件,我这里使用的Lambda表达式)
GlobalMouseHandler gmh = new GlobalMouseHandler();
bool mFlag = false;
int scY = ;
int msY = ;
Cursor tempCur = null; gmh.TheMouseMDown += () =>
{
mFlag = true;
scY = VerticalScroll.Value;
msY = Cursor.Position.Y;
tempCur = Cursor;
Cursor = RCurs.Pan;
};
gmh.TheMouseMoved += () =>
{
if (mFlag)
{
int val = scY + msY - Cursor.Position.Y;
if (val < VerticalScroll.Minimum) val = VerticalScroll.Minimum;
if (val > VerticalScroll.Maximum) val = VerticalScroll.Maximum;
VerticalScroll.Value = val;
}
};
gmh.TheMouseMUp += () =>
{
mFlag = false;
Cursor = tempCur;
};
Application.AddMessageFilter(gmh); //Application在Max中无效
二、鼠标勾子,此法亦在Max中行不通(后来是通过对FlowLayoutPanel中的各个控件实行事件穿透解决的)
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("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); hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[]), ); //如果装置失败停止钩子
if (hMouseHook == )
{
Stop();
throw new Exception("SetWindowsHookEx failed."); //Max中会抛出异常
}
}
} 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_MBUTTONDOWN:
button = MouseButtons.Middle;
clickCount = ;
break;
case WM_MBUTTONUP:
button = MouseButtons.Middle;
clickCount = ;
break;
} //从回调函数中得到鼠标的信息
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
MouseEventArgs e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, );
//if(e.X>700)return 1;//如果想要限制鼠标在屏幕中的移动区域可以在此处设置
OnMouseActivity(this, e);
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
}
调用的方法为:
MouseHook mouse = new MouseHook();
mouse.OnMouseActivity += (s, e) =>
{
string str = "X:" + e.X + " Y:" + e.Y + " " + e.Button + " " + e.Clicks;
this.Text = str;
};
mouse.Start();
三、鼠标事件模拟
//切换到窗口
[DllImport("user32.dll")]
public static extern bool SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
//获取鼠标所在窗口名柄
[DllImport("user32.dll")]
internal static extern IntPtr WindowFromPoint(Point Point);
[DllImport("user32.dll")]
internal static extern bool GetCursorPos(out Point lpPoint);
public static IntPtr GetMouseWindow()
{
Point p;
GetCursorPos(out p);
return WindowFromPoint(p);
}
//获取前台窗口
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow(); /// <summary>
/// 模拟鼠标操作
/// </summary>
[DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
//移动鼠标
const int MOUSEEVENTF_MOVE = 0x0001;
//模拟鼠标左键按下
const int MOUSEEVENTF_LEFTDOWN = 0x0002;
//模拟鼠标左键抬起
const int MOUSEEVENTF_LEFTUP = 0x0004;
//模拟鼠标右键按下
const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
//模拟鼠标右键抬起
const int MOUSEEVENTF_RIGHTUP = 0x0010;
//模拟鼠标中键按下
const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
//模拟鼠标中键抬起
const int MOUSEEVENTF_MIDDLEUP = 0x0040;
//标示是否采用绝对坐标
const int MOUSEEVENTF_ABSOLUTE = 0x8000;
public static void MouseMove(int x, int y)
{
mouse_event(MOUSEEVENTF_MOVE, x, y, , );
}
public static void MouseClick()
{
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, , , , ); //再复制一份则为双击
}
public static void MouseDown()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, , , , );
}
public static void MouseUp()
{
mouse_event(MOUSEEVENTF_LEFTUP, , , , );
}
c#全局鼠标事件以及鼠标事件模拟的更多相关文章
- 手持设备点击响应速度,鼠标事件与touch事件的那些事
前言 现在一直在做移动端的开发,这次将单页应用的网页内嵌入了app,于是老大反映了一个问题:app应用点击响应慢!我开始不以为然,于是拿着网页版的试了试,好像确实有一定延迟,于是开始了研究,最后选择了 ...
- jQuery-3.事件篇---鼠标事件
jQuery鼠标事件之click与dbclick事件 用交互操作中,最简单直接的操作就是点击操作.jQuery提供了两个方法一个是click方法用于监听用户单击操作,另一个方法是dbclick方法用于 ...
- Selenium3 + Python3自动化测试系列四——鼠标事件和键盘事件
一.鼠标事件 在 WebDriver 中, 将这些关于鼠标操作的方法封装在 ActionChains 类提供. ActionChains 类提供了鼠标操作的常用方法. ActionChains 类的成 ...
- jQuery基础(鼠标事件,表单事件,键盘事件,自定义事件 篇)
1.jQuery鼠标事件之click与dbclick事件 方法一:$ele.click()(不带参数) <div id="test">点击触发<div&g ...
- 整理之DOM事件阶段、冒泡与捕获、事件委托、ie事件和dom模型事件、鼠标事件
整理之DOM事件阶段 本文主要解决的问题: 事件流 DOM事件流的三个阶段 先理解流的概念 在现今的JavaScript中随处可见.比如说React中的单向数据流,Node中的流,又或是今天本文所讲的 ...
- Qt事件系统之二:鼠标事件和滚轮事件
在Qt中,事件作为一个对象,继承自 QEvent 类,常见的有键盘事件 QKeyEvent.鼠标事件 QMouseEvent 和定时器事件 QTimerEvent 等,与 QEvent 类的继承关系图 ...
- JQuery事件之鼠标事件
鼠标事件是在用户移动鼠标光标或者使用任意鼠标键点击时触发的. ():click事件:click事件于用户在元素敲击鼠标左键,并在相同元素上松开左键时触发. $('p').click(function( ...
- 鼠标焦点变化引起mouseout事件
做了个小手术,渐渐回归网络啦! 问题: 在自制的提示离鼠标太近时,会引起无法提示的功能. 自制提示离图片太近时,提示图片一直一闪一闪的,截图截不出来,就只放改善后的图片(不闪). 原因: 为什么呢?书 ...
- jQuery编程基础精华03(RadioButton操作,事件,鼠标)
RadioButton操作 取得RadioButton的选中值,被选中的radio只有一个值,所以直接用val() $('#btn1').click(function () { ...
随机推荐
- X86 Socket 通信
struct txd_socket_handler_t { int fd; }; txd_socket_handler_t *txd_tcp_socket_create() { txd_socket_ ...
- POJ题目排序的Java程序
POJ 排序的思想就是根据选取范围的题目的totalSubmittedNumber和totalAcceptedNumber计算一个avgAcceptRate. 每一道题都有一个value,value ...
- toggle()方法和hove()方法
toggle()语法结构: toggle(fn1,fn2,fn3,....fnN); 第一次单击元素,触发第一个元素,再次单击触发第二个元素,如果有更多元素,依次触发,直到最后一个元素,随后单击反复对 ...
- SQLServer 自增主键创建, 指定自增主键列值插入数据,插入主键
http://blog.csdn.net/zh2qiang/article/details/5323981 SQLServer 中含自增主键的表,通常不能直接指定ID值插入,可以采用以下方法插入. 1 ...
- 分析案例:应用服务器W3WP进程CPU持续超过百分之九十(Oracle客户端Bug)
问题描述: 项目反馈应用负载的其中一台服务器业务操作的响应非常慢,登录该服务器发现W3WP进程CPU持续超过90%,哪怕在业务低峰期也是如此?远程查看后发现该应用服务器承载的请求确实很低,why??? ...
- Android应用开发-网络编程(二)(重制版)
Apache HttpClient框架 GET方式请求提交数据 1. 创建一个HttpClient HttpClient hc = new DefaultHttpClient(); 2. 创建一个Ht ...
- An invalid character [32] was present in the Cookie value
系统安装Tomcat版本为:tomcat8,登录时报错"An invalid character [32] was present in the Cookie value" 处理方 ...
- linux---mysql安装
一.查询本机是否有mysql service mysql status 二.检查已安装的mysql版本 mysql –uroot -p status 三.查看已安装的mysql的组件 dpkg --g ...
- Android引用项目出现ClassNotFoundException
Android中在引用其他工程,尤其是github中的相关库时,如果引用关系设置的不对,很容易出现ClassNotFoundException,例如下面的异常信息 07-26 12:47:51.549 ...
- keil中出现Undefined symbol FLASH_PrefetchBufferCmd (referred from main.o)等问题解决办法
在keil中仿照别人的程序写了RCC初始化的程序,编译后出现以下问题 .\obj\pro1.axf: Error: L6218E: Undefined symbol FLASH_PrefetchBuf ...