【发布时间】:2019-04-14 07:27:20
【问题描述】:
我正在尝试编写应用程序,当用户长按鼠标左键时,它将发送右键单击。
我找到了https://github.com/gmamaladze/globalmousekeyhook 项目并用它挂钩了事件。
当我挂上左键,然后用鼠标事件发送右键单击,首先触发左键,然后右键触发。
有什么方法可以取消第一次鼠标左键按下吗?
using Gma.System.MouseKeyHook;
using System;
using System.Windows.Forms;
namespace MouseRClick
{
class ClassRightClick
{
// API
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;
// Hook module
private IKeyboardMouseEvents _hook;
private bool _rclick_activated = false;
private int _down_cursor_x;
private int _down_cursor_y;
private Timer timer;
public ClassRightClick(int delay)
{
timer = new Timer();
timer.Interval = delay;
timer.Tick += timer_Tick;
}
public void Subscribe()
{
_hook = Hook.GlobalEvents();
_hook.MouseDownExt += onMouseDown;
_hook.MouseUpExt += onMouseUp;
}
public void Unsubscribe()
{
_hook.MouseDownExt -= onMouseDown;
_hook.MouseUpExt -= onMouseUp;
//It is recommened to dispose it
_hook.Dispose();
}
private void onMouseDown(object sender, MouseEventExtArgs e)
{
if (e.Button == MouseButtons.Left)
{
_down_cursor_x = e.Location.X;
_down_cursor_y = e.Location.Y;
_rclick_activated = false;
timer.Enabled = true;
}
}
private void onMouseUp(object sender, MouseEventExtArgs e)
{
if (e.Button == MouseButtons.Left)
{
timer.Enabled = false;
Unsubscribe();
if (_rclick_activated)
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, _down_cursor_x, _down_cursor_y, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTUP, _down_cursor_x, _down_cursor_y, 0, 0);
e.Handled = true;
}
_rclick_activated = false;
Subscribe();
}
}
private void timer_Tick(object sender, EventArgs e)
{
_rclick_activated = true;
}
}
}
【问题讨论】:
-
为什么要取消鼠标左键的第一次按下?你可以用不同的方式处理它。并且mouse_event 功能已被取代。请改用SendInput。
-
我已经尝试防止鼠标左键按下,如果按钮被快速释放发送左键,或者如果它释放长发送右。这是可行的,但是在按下元素更改显示之前,快速左键单击会产生丑陋的 UI 延迟。
标签: c# winapi mouseevent mousekeyhook