簡體   English   中英

如何檢測按下的鍵?

[英]How to detect a pressed key?

我有一個大學作業,我必須將字符串作為輸入並在用戶按 CTRL + z 時停止程序,然后顯示最長和最短的字符串。 我的 Z 沒問題,但我似乎無法檢測到用戶是否按下了 CTRL z。

我嘗試使用 (ki.Modifiers & ConsoleModifiers.Control) 但它沒有用。 這是代碼

Console.Write("Enter a string: ");
String input = Console.ReadLine();
String l = input;
String s = input;
ConsoleKeyInfo ki = new ConsoleKeyInfo();

while (ki.Key != ConsoleKey.Z )
{
    Console.Write("Enter another string: ");
    input = Console.ReadLine();

    if (input.Length > l.Length) l = input;
    else if (input.Length < s.Length) s = input;
    Console.WriteLine("Press enter to continue or <CTRL> + Z to exit");
    ki = Console.ReadKey(true);
}
Console.WriteLine("Longest string: " + l);
Console.WriteLine("Shortest string: " + s);
Console.ReadLine();

了解如何使用調試器和調試。 如果在第 16 行設置斷點,您可能會發現以下內容:

調試器信息

放入代碼:

!(ki.Key == ConsoleKey.Z && ki.Modifiers == ConsoleModifiers.Control)

或者簡單地

ki.KeyChar != 26

正如@Hans Passant 在評論中提到的,當按下 Ctrl+Z(和 Enter)時, ReadLine()返回null ,因此您可以將代碼簡化為

Console.Write("Enter a string: ");
var s = Console.ReadLine();
var l = s;

while (true)
{
    Console.Write("Enter another string or Ctrl+Z to end input: ");
    string input = Console.ReadLine();
    if (input == null) break;

    if (input.Length > l.Length) l = input;
    else if (input.Length < s.Length) s = input;
}
Console.WriteLine("Longest string: " + l);
Console.WriteLine("Shortest string: " + s);
Console.ReadLine();

暫無
暫無

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

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