如何检查控制台应用程序中是否按下了 CTRL 键 C#

Nau*_*lus 6 c# ctrl console.readkey

我要启动一个控制台应用程序。问题是如何确定 CTRL 键是单独按下的,没有任何其他键。

using System;
using System.Text;

public class ConsoleKeyExample
{
   public static void Main()
    {

       ConsoleKeyInfo input;
       do
       {
           input = Console.ReadKey(true);
           StringBuilder output = new StringBuilder(String.Format("You pressed {0}",input.Key.ToString()));

           Console.WriteLine(output.ToString());
           if ((input.Modifiers & ConsoleModifiers.Control) != 0)
           {
               Console.WriteLine("CTRL Pressed");
            }
       } while (input.Key != ConsoleKey.Escape);
   }
  }
Run Code Online (Sandbox Code Playgroud)

我想监视 CTRL 键的行为。跟踪此代码后,我在 readkey 行上放置了一个检查点,但是当我按下 CTRL 时,什么也没有发生,但是当我按下任何其他键(如“K”)时,它开始从键盘读取键。

Men*_*nol 7

除非您使用的 .Net 框架早于 4.0 版,否则我相信使用Enum.HasFlag()比使用按位 AND 更具可读性。

例如

if (cki.Modifiers.HasFlag(ConsoleModifiers.Control))
{
   Console.Write("CTRL ");
}
Run Code Online (Sandbox Code Playgroud)

我不确定为什么 MSDN 文章没有更新为使用标志,因为 ConsoleModifiers 确实支持 Flags 属性。

以下是适用于框架 4.0 及更高版本的同一程序的更新副本。

static void Main(string[] args)
{
    ConsoleKeyInfo cki;

    Console.WriteLine("Press Esc to exit the loop");

    do
    {
        cki = Console.ReadKey(true);

        if (cki.Modifiers.HasFlag(ConsoleModifiers.Control))
        {
            Console.Write("CTRL ");
        }

        if (cki.Modifiers.HasFlag(ConsoleModifiers.Alt))
        {
            Console.Write("ALT ");
        }

        if (cki.Modifiers.HasFlag(ConsoleModifiers.Shift))
        {
            Console.Write("SHIFT ");
        }

        Console.WriteLine(cki.Key.ToString());

    } while (cki.Key != ConsoleKey.Escape);


    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

是的,可以通过使用ConsoleKeyInfo. 例子:

public static void Main() 
{
  ConsoleKeyInfo cki;
  // Prevent example from ending if CTL+C is pressed.
  Console.TreatControlCAsInput = true;

  Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
  Console.WriteLine("Press the Escape (Esc) key to quit: \n");
  do 
  {
     cki = Console.ReadKey();
     Console.Write(" --- You pressed ");
     if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
     if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
     if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
     Console.WriteLine(cki.Key.ToString());
   } while (cki.Key != ConsoleKey.Escape);
}
Run Code Online (Sandbox Code Playgroud)

虽然仅适用于 .NET Framework 4.6 和 4.5

  • 为什么不包含 MSDN 文章的链接,其中包含更多有用的信息,https://msdn.microsoft.com/en-us/library/system.consolekeyinfo(v=vs.110).aspx (2认同)