捕获击键没有焦点控制台 [英] Capture keystroke without focus in console

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

问题描述

我知道有Windows窗体的一个问题,但它在控制台不工作,或者至少我不能得到它的工作。我需要捕捉关键presses即使不必须重点控制台

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.

下面是完整的,工作code:

Here's complete, working code:

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

您创建的控制台应用程序的,但必须在引用的 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.

修改

主线程将运行Application.Run(),直到退出应用程序,例如通过以Application.Exit()的调用。做其他的工作,最简单的方法是开始一个新的任务来完成这项工作。下面是从链接code,这是否主要()的修改版

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

注意

可能提供退出控制台应用程序例如一种手段当一个特殊的组合键是$ P $根据您的具体需求pssed。在

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天全站免登陆