在控制台中捕获没有焦点的击键

Capture keystroke without focus in console(在控制台中捕获没有焦点的击键)
本文介绍了在控制台中捕获没有焦点的击键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个关于 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

这篇关于在控制台中捕获没有焦点的击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)