2012-01-17 88 views
23

我想創建一個控制檯應用程序將顯示按下控制檯屏幕上的鍵,我迄今取得驗證碼:如何處理在控制檯應用程序按鍵事件

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

我想知道,我應該輸入什麼內容才能打電話給該事件?

回答

20

對於控制檯應用程序,你可以做到這一點,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

12

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

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對象,它封裝了大量有關其的按鍵信息。

相關問題