简体   繁体   English

如何使控制台应用程序侦听来自其他进程的按键?

[英]How to make Console App listen for keypresses from other processes?

I'm new to C# programming and I'm attempting to write a Console App that will run in the background and perform an action when a key is pressed (ideally I would like to know how to do this for any key but, if that's not possible, then a specific key). 我是C#编程的新手,我正在尝试编写一个将在后台运行的控制台应用程序,并在按下某个键时执行操作(理想情况下,我想知道如何为任何键执行此操作,但是,如果这是不可能,然后是一个特定的键)。

Here's an idea of what I want (please excuse and feel free to correct any bad coding as I'm just starting out). 这是我想要的想法(请原谅并随意纠正任何不良编码,因为我刚刚开始)。

public static void Main(string[] args)
{
    while(true)
    {
         ConsoleKeyInfo cki = Console.ReadKey();
         if( cki.Key == ConsoleKey.R )
         {
              Console.WriteLine("Run me");
         }
     }
 }

The above seems to work but only if the Console App is in focus. 以上似乎可行,但仅限于控制台应用程序是焦点。 I would like it to happen even if the app isn't in focus. 即使应用程序不是焦点,我也希望它发生。

I've done some research and read about registering 'hotkeys' but also read that this is dangerous in case another application is requiring that key? 我做过一些研究并阅读有关注册“热键”的内容,但也读到这是危险的,以防另一个应用程序需要该密钥?

I've also read similar questions on here but they seem to deal with Windows Forms and not just Console Apps. 我也在这里阅读了类似的问题,但它们似乎只涉及Windows Forms而不仅仅是Console Apps。

Can anyone help shed any light on this? 任何人都可以帮助解决这个问题吗?

You need to use 你需要使用

[DllImport("user32", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

But to make it work from console you'll need to create hidden form that will handle messages for you. 但要使其在控制台上运行,您需要创建隐藏的表单,以便为您处理消息。 Check out this class . 看看这堂课 It does exactly what you want. 它完全符合你的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM