I have a simple console application written in C #. I want to be able to detect arrow keystrokes, so I can allow the user to control. How to detect keydown / keyup events using a console application?
All my googling led to information on Windows Forms. I do not have a graphical interface. This is a console application (for controlling the robot via the serial port).
I have functions written to handle these events, but I have no idea how to register to actually receive the events:
private void myKeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: ... case Keys.Right: ... case Keys.Up: ... } } private void myKeyUp(object sender, KeyEventArgs e) { ... pretty much the same as myKeyDown }
This is probably really the main question, but I'm pretty new to C #, and I never had to enter this input before.
Update:. Many of them suggest using System.Console.ReadKey(true).Key
. This will not help. I need to know the moment when the key is held, when it is released, while holding several keys at the same time. In addition, ReadKey is a blocking call, which means that the program will stop and wait for the key to be pressed.
Update: It seems that the only way to do this is to use Windows Forms. This is annoying because I cannot use it in a headless system. Requiring a Form GUI to enter keyboard input ... is silly.
But in any case, for posterity, here is my solution. I created a new form project in my .sln:
private void Form1_Load(object sender, EventArgs e) { try { this.KeyDown += new KeyEventHandler(Form1_KeyDown); this.KeyUp += new KeyEventHandler(Form1_KeyUp); } catch (Exception exc) { ... } } void Form1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { // handle up/down/left/right case Keys.Up: case Keys.Left: case Keys.Right: case Keys.Down: default: return; // ignore other keys } } private void Form1_KeyUp(object sender, KeyEventArgs e) { // undo what was done by KeyDown }
Note that if you hold the key, KeyDown will be called many times, and KeyUp will be called only once (when you release it). Therefore, you must handle repeated KeyDown calls gracefully.