简体   繁体   English

检测C#控制台应用程序中按下的组合键

[英]Detect key combination being pressed in C# console app

I have a pretty simple console app thats quietly waits for a users to press a key, then performs an action based on the what key was pressed. 我有一个非常简单的控制台应用程序,它安静地等待用户按下某个键,然后根据所按下的键执行操作。 I had some issues with it, but some helpful users over on this post pointed out where I was going wrong. 我遇到了一些问题,但是这篇文章上的一些有用的用户指出了我出了错。

The code I currently have to handle a single key press is as follows 我当前要处理一次按键的代码如下

ConsoleKey key;
do
{
    while (!Console.KeyAvailable)
    {
        // Do something, but don't read key here
    }

    // Key is available - read it
    key = Console.ReadKey(true).Key;

    if (key == ConsoleKey.NumPad1)
    {
        Console.WriteLine(ConsoleKey.NumPad1.ToString());
    }
    else if (key == ConsoleKey.NumPad2)
    {
        Console.WriteLine(ConsoleKey.NumPad2.ToString());
    }

} while (key != ConsoleKey.Escape);

I'm wondering how I can detect when a combination of 2 or more keys is pressed. 我想知道如何才能检测到何时按下两个或更多键的组合。 I'm not talking about the standard Ctrl + c , but rather something like Ctrl + NumPad1 . 我不是在谈论标准的Ctrl + c ,而是像Ctrl + NumPad1之类的东西。 If a user presses Ctrl + NumPad1 , perform action X . 如果用户按下Ctrl + NumPad1 ,请执行操作X

I'm really unsure how to go about doing this, as the current while loop will only loop until a single key is pressed, so wont detect the second key (assuming that its litterally impossible to press two keys at the exact same time. 我真的不确定如何执行此操作,因为当前的while循环将一直循环直到按下单个键为止,因此不会检测到第二个键(假设它几乎完全不可能同时按下两个键。

Is anyone able to provide a steer in the right direction to help achieve this? 有谁能够提供正确方向的指导以帮助实现这一目标?

I guess you need to check the key modifier . 我猜您需要检查key修饰符 Check the pseudo code below: 检查下面的伪代码:

ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine(keyInfo.Key);
Console.WriteLine(keyInfo.Modifier);
...
if((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) Console.WriteLine("CTL+");

If you capture the ConsoleKeyInfo , you will get additional information, including the Modifiers keys. 如果捕获ConsoleKeyInfo ,则将获得其他信息,包括Modifiers键。 You can query this to see if the Control key was pressed: 您可以查询以下内容以查看是否按下了Control键:

ConsoleKey key;

do
{
    while (!Console.KeyAvailable)
    {
        // Do something, but don't read key here
    }

    // Key is available - read it
    var keyInfo = Console.ReadKey(true);
    key = keyInfo.Key;

    if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
    {
        Console.Write("Ctrl + ");
    }
    if (key == ConsoleKey.NumPad1)
    {                    
        Console.WriteLine(ConsoleKey.NumPad1.ToString());
    }
    else if (key == ConsoleKey.NumPad2)
    {
        Console.WriteLine(ConsoleKey.NumPad2.ToString());
    }

} while (key != ConsoleKey.Escape);

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

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