问题描述
我知道有一个关于 Windows 窗体的问题,但它在控制台中不起作用,或者至少我无法让它起作用.即使控制台没有焦点,我也需要捕获按键.
I know there is a question for Windows Forms but it doesn't work in the console, or at least I couldn't get it to work. I need to capture key presses even though the console doesn't have focus.
推荐答案
您也可以在控制台应用程序中创建全局键盘挂钩.
You can create a global keyboard hook in a console application, too.
这是完整的工作代码:
https://docs.microsoft.com/en-us/archive/blogs/toub/low-level-keyboard-hook-in-c
您创建了一个控制台应用程序,但必须添加对System.Windows.Forms 的引用才能使其工作.控制台应用程序没有理由不能引用该 dll.
You create a console application, but must add a reference to System.Windows.Forms for this to work. There's no reason a console app can't reference that dll.
我刚刚使用此代码创建了一个控制台应用程序,并验证了它是否按下了每个键,无论控制台应用程序是否具有焦点.
I just created a console app using this code and verified that it gets each key pressed, whether or not the console app has the focus.
编辑
主线程将运行 Application.Run() 直到应用程序退出,例如通过调用 Application.Exit().完成其他工作的最简单方法是启动一个新任务来执行该工作.这是执行此操作的链接代码中 Main() 的修改版本
The main thread will run Application.Run() until the application exits, e.g. via a call to Application.Exit(). The simplest way to do other work is to start a new Task to perform that work. Here's a modified version of Main() from the linked code that does this
public static void Main()
{
var doWork = Task.Run(() =>
{
for (int i = 0; i < 20; i++)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
Application.Exit(); // Quick exit for demonstration only.
});
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
注意
可能提供退出控制台应用程序的方法,例如根据您的特定需求按下特殊组合键时.在
Possibly provide a means to exit the Console app, e.g. when a special key combo is pressed depending on your specific needs. In the
这篇关于在控制台中捕获没有焦点的击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!