在控制台中捕获没有焦点的按键 [英] Capture keystroke without focus in console

查看:168
本文介绍了在控制台中捕获没有焦点的按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Windows窗体有一个问题,但它在控制台中不起作用,或至少我无法使其正常工作。我需要捕获按键,即使控制台没有焦点

解决方案

您可以在控制台应用程序中创建全局键盘钩子,



以下是完整的工作代码:



http://blogs.msdn.com/b/toub/archive/2006/05/03/589423。 aspx



您创建了一个控制台应用程序,但必须添加对 System.Windows.Forms 为此工作。没有理由控制台应用程序无法引用该DLL。



我刚刚使用此代码创建控制台应用程序,并验证它是否按下每个按键,无论控制台是否应用程序有焦点。



编辑



主线程将运行应用程序。 Run()直到应用程序退出,例如通过调用Application.Exit()。执行其他工作的最简单的方法是启动一个新的Task来执行这项工作。这是一个修改版本的Main()从链接代码执行这个

  public static void Main()
{
var doWork = Task.Run(()=>
{
for(int i = 0; i <20; i ++)
{
控制台。 WriteLine(i);
Thread.Sleep(1000);
}
Application.Exit(); //快速退出仅用于演示
});

_hookID = SetHook(_proc);

Application.Run();

UnhookWindowsHookEx(_hookID);
}

注意



可能提供退出控制台应用程序的方法,例如当根据您的具体需要按下特殊键组合时。在


I know there is a question for windows forms but it doesnt work in the console, or at least i couldnt get it to work. I need to capture key presses even though the console doesnt have focus

解决方案

You can create a global keyboard hook in a console application, too.

Here's complete, working code:

http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

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 console app using this code and verified that it gets each key pressed, whether or not the console app has the focus.

EDIT

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);
}

NOTE

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆