在过去的几个小时里,我一直在研究如何检测全局鼠标左键点击(不集中),偶然发现了多篇提到使用globalmousekeyhook的帖子,这是我通过NuGet安装的,我已经实现了如下代码:
using Gma.System.MouseKeyHook;
using System;
namespace mouse_hook_test
{
class Program
{
static private IKeyboardMouseEvents m_GlobalHook;
static void Main(string[] args)
{
Subscribe();
Console.ReadKey();
}
static public void Subscribe()
{
m_GlobalHook = Hook.GlobalEvents();
m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
}
static private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
Console.WriteLine("Mouse Click.");
}
}
}当我运行它时,我的屏幕上的鼠标突然开始滞后到无法使用的地步(我甚至努力关闭命令提示符),我也尝试过左右单击,但没有任何记录。我是不是做了件很愚蠢的事?我觉得我遗漏了一些很明显的东西,因为没有其他人有这个问题,或者如果有其他解决方案,我很乐意尝试一下。谢谢。
Visual Studio 2019,Windows10专业版,项目:.NET框架4.7.2,控制台应用程序,使用调试模式运行
发布于 2021-01-03 09:41:31
我实际上是像往常一样,寻找不同的方法,然后偶然发现了Windows API function for getting states of keys (GetKeyStates) (包括鼠标),所以我导入了user32 DLL,并启动了一个循环,每50ms检查一次鼠标左键状态(0x01) (发现这是最好的时间),并将其抛入一个线程中,这样它就不会阻塞主要的状态。
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace mouse_hook_test
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(detect);
thread.Start();
}
// Import the DLL that contains the function and grab it.
[DllImport("user32.dll")]
public static extern short GetKeyState(int vKey);
// A very simple implementation for tracking the state of the left mouse button.
static void detect()
{
short oldState = GetKeyState(0x01);
while (true)
{
short newState = GetKeyState(0x01);
if (oldState != newState)
{
oldState = newState;
if (newState < 0)
{
onMouseClick();
}
}
Thread.Sleep(50);
}
}
static void onMouseClick()
{
Console.WriteLine("Clicked!");
}
}
}可能有一个更好的解决方案(我找不到),所以我为什么要使用这个。我最初是根据这个问题的答案编写的,但它是用Python语言编写的,所以我将其转换为C#。我已经厌倦了看到我的问题的唯一答案是“使用一些第三方库”,无论出于什么原因,它对我来说都不能正常工作,并且还将内存使用量从30mb减少到7mb :)。
我还在Windows7上测试了它,它工作得非常好。
发布于 2020-12-31 09:09:13
这是因为消息是由全局钩子发送到线程的Win32消息队列的。这与在表单中将消息传递给WndProc所使用的队列相同。
要接收消息,您必须使用Application.Run()抽出消息队列。但在控制台应用程序中,没有Application.Run()。
已经有了various solutions give,但我认为下面的可能是最好的。
using Gma.System.MouseKeyHook;
using System;
using System.Windows.Forms;
namespace mouse_hook_test
{
class Program
{
static private IKeyboardMouseEvents m_GlobalHook;
static void Main(string[] args)
{
//Run pump on another background thread
//Task.Run feels like a bad idea without a pump/synchronisation context
var pumpThread = new Thread(PumpQueue){IsBackground = true};
pumpThread.Start();
Console.ReadKey();
Application.Exit(); // closes down the pump
}
[STAThread] // I think this is necessary to ensure thread-safety
static PumpQueue()
{
Subscribe();
Application.Run();
}
static public void Subscribe()
{
m_GlobalHook = Hook.GlobalEvents();
m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
}
static private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
Console.WriteLine("Mouse Click.");
}
}
}https://stackoverflow.com/questions/65515339
复制相似问题