Reputation: 41
I want to make a little game. The program will output numbers in a loop, and the person has to stop the loop in the exact number that was specified before, by clicking the 'enter' key. like so:
static void Main(string[] args)
{
Console.WriteLine("try to click the 'enter' button when the program shows the number 4");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
//here will be the command which reads the enter key and stops the loop
}
}
One of the users told me to use this code:
Console.WriteLine("try to click the 'enter' button when the program shows the number 4");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
if (e.KeyChar == (char)13)
{
break;
}
}
The problem is, when i use this code, i have an error which says 'the name 'e' does not exist in the current context'. What does that mean?
Upvotes: 0
Views: 5083
Reputation: 338
I found a basic idea for a solution to your problem here.
In this answer he is using the Console.KeyAvaliable
property to check if a Key has been pressed and then checks if the press key is the one you are lookig for.
To fit it to your needs you have to change it like so:
static void Main (string[] args)
{
Console.WriteLine ("try to click the 'enter' button when the program shows the number 4");
int counter = 0;
int limit = 100000;
do {
while (counter < limit && !Console.KeyAvailable) {
Console.WriteLine (counter);
counter++;
}
} while (Console.ReadKey (true).Key != ConsoleKey.Enter);
}
Upvotes: 1
Reputation: 480
Try:
ConsoleKeyInfo cki;
do
{
cki = Console.ReadKey();
//What you need to do code
} while (cki.Key != ConsoleKey.Enter);
Console.ReadKey()
will wait for a keypress and return it as a ConsoleKey, you just catch and test if it's your desired key.
Upvotes: 0
Reputation: 16584
There are two basic methods for reading console input:
Console.ReadLine()
will pause and wait for the user to enter text followed by the enter key, returning everything entered before the enter key is pressed as a string.
Console.ReadKey()
will wait for a keypress and return it as a ConsoleKeyInfo
structure with information on the key pressed, what character (if any) it represents and what modifier keys (ctrl, alt, shift) were pressed.
If you don't want to wait until the user presses a key you can use the Console.KeyAvailable
property to check if there is a keypress waiting to be read. This can be used in a timing loop to provide a timeout for key entry:
DateTime endTime = DateTime.Now.AddSeconds(10);
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Enter)
{
// do something with key
//...
// stop waiting
break;
}
}
// sleep to stop your program using all available CPU
Thread.Sleep(0);
}
Upvotes: 2