-1

I have the following lines of code in my Console Application in C#:

public static bool ReadKey(int key)
{
    /* Is the key represented by `key` pressed? */
}

How am I able to retrieve the right keyboard key?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Encore
  • 275
  • 2
  • 12
  • C#? Java? Other? Please tag the useful things, like language. [tag:numbers], [tag:key], and [tag:pressed] should never be used. – Ry- Jan 26 '14 at 15:40
  • What language and platform? – some Jan 26 '14 at 15:40
  • Oh sorry forgot its a console app in c# – Encore Jan 26 '14 at 15:43
  • Are you talking about keyboard keys? http://www.asciitable.com/ – mika Jan 26 '14 at 15:43
  • What’s the context? Why do you need to check whether a key’s been pressed? – Ry- Jan 26 '14 at 15:48
  • A piece of advice about tags: Always include what language you are using. – some Jan 26 '14 at 15:48
  • I want to invoke different methods according to the key that is pressed on the keyboard, so i need to know which key is pressed. – Encore Jan 26 '14 at 15:51
  • But what’s the real context? Are you building a game? A command-line utility? A keyhook-type thing? – Ry- Jan 26 '14 at 16:46
  • It is a simulation of opening a Gate, which we are doing in school. So if the key "1" on the keyboard is pressed the OpenGate Method should be invoked and if "2" is pressed the Close Gate Method should be invoked etc.. So my idea was to have a while loop, where the condition is that the key "1" should be pressed. Something like while(ReadKey(1)){} (The Method is in the OP) and if it is pressed return true, else return false. So when the key is pressed it breaks out of the loop and continues with opening the Gate. In school we should open a Gate with the MicroController "K8055". – Encore Jan 26 '14 at 17:57

1 Answers1

1

If you're application needs to be executing without pause and in that execution you need to check if key is pressed then: You can't do that in c# console application.

Take a look into first answer in this question. Same thing, you just need to modify it to support all needed keys instead of just arrow keys

C# arrow key input for a console app

or

If the case is that you need to wait for user input, the simplest solution is Console.ReadKey();

Community
  • 1
  • 1
Aleksandar Toplek
  • 2,792
  • 29
  • 44
  • Is it possible to do this Console.Readkey();, but if there is no input for like 5 seconds it breaks out of this Method? (I'm very new to programming, so this might be a stupid question) – Encore Jan 26 '14 at 17:59
  • Take a look into this: http://stackoverflow.com/questions/57615/how-to-add-a-timeout-to-console-readline – Aleksandar Toplek Jan 26 '14 at 18:53