簡體   English   中英

如何處理控制台應用程序中的按鍵事件

[英]How to handle key press event in console application

我想創建一個控制台應用程序,它將顯示在控制台屏幕上按下的鍵,到目前為止我編寫了以下代碼:

    static void Main(string[] args)
    {
        // this is absolutely wrong, but I hope you get what I mean
        PreviewKeyDownEventArgs += new PreviewKeyDownEventArgs(keylogger);
    }

    private void keylogger(KeyEventArgs e)
    {
        Console.Write(e.KeyCode);
    }

我想知道,我應該在 main 中輸入什么才能調用該事件?

對於控制台應用程序,您可以執行此操作, do while循環會一直運行,直到您按x

public class Program
{
    public static void Main()
    {

        ConsoleKeyInfo keyinfo;
        do
        {
            keyinfo = Console.ReadKey();
            Console.WriteLine(keyinfo.Key + " was pressed");
        }
        while (keyinfo.Key != ConsoleKey.X);
    }
}

這僅在您的控制台應用程序具有焦點時才有效。 如果你想收集系統范圍內的按鍵事件,你可以使用windows hooks

不幸的是 Console 類沒有為用戶輸入定義任何事件,但是如果您希望輸出當前按下的字符,您可以執行以下操作:

 static void Main(string[] args)
 {
     //This will loop indefinitely 
     while (true)
     {
         /*Output the character which was pressed. This will duplicate the input, such
          that if you press 'a' the output will be 'aa'. To prevent this, pass true to
          the ReadKey overload*/
         Console.Write(Console.ReadKey().KeyChar);
     }
 }

Console.ReadKey返回一個ConsoleKeyInfo對象,該對象封裝了大量有關按下的鍵的信息。

另一個解決方案,我將它用於基於文本的冒險。

        ConsoleKey choice;
        do
        {
           choice = Console.ReadKey(true).Key;
            switch (choice)
            {
                // 1 ! key
                case ConsoleKey.D1:
                    Console.WriteLine("1. Choice");
                    break;
                //2 @ key
                case ConsoleKey.D2:
                    Console.WriteLine("2. Choice");
                    break;
            }
        } while (choice != ConsoleKey.D1 && choice != ConsoleKey.D2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM