0

Can somebody give me a snippet, about event when a user presses Down Arrow button or Up Arrow button, in console something to be triggered example

 Console.WriteLine("You have pressed up/down arrow ");

maybe that is a stupid question, but i can't find it with events but i need to be with events, any help is welcomed.

Curtis
  • 101,612
  • 66
  • 270
  • 352
Yoan Dinkov
  • 531
  • 1
  • 5
  • 17

3 Answers3

2

Here's a loop which does that repeatedly until the user presses Ctrl+C:

while (true)
{
    ConsoleKeyInfo key = Console.ReadKey();

    if (key.Key == ConsoleKey.UpArrow || key.Key == ConsoleKey.DownArrow)
    {
        Console.WriteLine("You have pressed up/down arrow ");
    }
}

That should do it.

Steve Westbrook
  • 1,698
  • 2
  • 20
  • 21
1

There are no UI events for console applications so you're stuck with Console.ReadKey();

paul
  • 21,653
  • 1
  • 53
  • 54
  • Well, that's OK, can't be done something like if Console.ReadKey == ConsoleKey.UpArrow Console.WriteLine("Up arrow is pressed"); – Yoan Dinkov Mar 18 '13 at 16:32
0

The console doesn't define those events. You can simulate something by using Console.ReadKey. You'd have to define your own events, then:

var key = Console.ReadKey();
// create event parameters and dispatch the event

Obviously, Console.ReadKey blocks on the console. You can put that in a thread if you want, and dispatch the event from there. Be advised, though, that the event notification will come in on a separate thread (i.e. not the main thread).

Also, you can't have two different threads reading from the same console. Well, you can, but the results are unpredictable. For example, if your background thread is waiting on a ReadKey and another thread calls Console.ReadLine(), there's no telling where the input will end up.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351