Easy
Easy

Reputation: 127

How to check if any of 2 possible keys is pressed with ConsoleKeyInfo?

I encountered a pretty dumb problem with ConsoleKeyInfo. I want do check if "1" is entered using either numpad or regular top numeric keys.

 ConsoleKeyInfo keyPressed;
 keyPressed = Console.ReadKey();
 if (keyPressed = ConsoleKey.D1 || keyPressed = ConsoleKey.NumPad1)
 { }

And for some reason I cant use "||" operator. Is it possible to somehow check it within 1 if loop without using Console.ReadLine(); and forcing user to press enter?

Upvotes: 1

Views: 584

Answers (1)

fubo
fubo

Reputation: 46005

You have to compare with == instead of =. Otherwise you're trying to assigning the value.

And you have to compare the Key property of ConsoleKeyInfo which holds the ConsoleKey enum.

So your if should look like:

if (keyPressed.Key == ConsoleKey.D1 || keyPressed.Key == ConsoleKey.NumPad1)

Upvotes: 5

Related Questions