danytb8
danytb8

Reputation: 1

How to detect a pressed key?

I have an assignment for college where I have to take strings as an input and stop the program if the user presses CTRL + z and then display the longest and shortest string. I got the Z alright but I can't seem to detect if the user pressed CTRL z.

I tried using (ki.Modifiers & ConsoleModifiers.Control) but it didn't work. here's the code

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

Upvotes: -2

Views: 356

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 59208

Learn how to use a debugger and debug. Here's what you may find if you set a breakpoint in line 16:

Debugger information

Put into code:

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

or simply

ki.KeyChar != 26

As mentioned by @Hans Passant in the comment, ReadLine() returns null when Ctrl+Z (and Enter) is pressed, so you can reduce your code to

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

Upvotes: 0

Related Questions