C# Console - Run Event on Key Press - c#

I just wanted to ask if it was possible to make an event run if the player presses a specific button. This should be tested at every point in the console application but not if there is a Console.ReadLine() event used at the moment.
Is there a way to do this?

You can use Console.ReadKey() method like this
ConsoleKeyInfo keyInfo = Console.ReadKey();
if(keyInfo.Key == ConsoleKey.A)
{
}
For more info see https://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Related

Stop Console Application from pausing on Pause Evemt

I've implememted a small Console Application that checks how long a programm is running. I then tried to run the application and everything is working fine. However then i hit (by accident) the "pause" key on my Keyboard and the programm stopped executing.
Is there a way to handle this event in a Console Application to suppress this pausing?
Update:
class Program
{
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(2000);
var p = Process.GetProcessesByName("wineks");
if (p != null)
{
Console.WriteLine("Found Process. Close it please");
Console.ReadKey();
}
}
}
}
That is basically my code. It is only asking the user to close a specific process. If I know hit the Pause Button on my Keyboard before I see the message, the message will never appear because the application freezes and seems like paused.
From browsing in the Internet I know that the key I press has the Name Pause and the key is sending some kind of Event or Signal to the Console.
Actually the Console does not have a way to raise KeyPress events , you can however try some looped approach to handle any key press done accidentally . Refer to this stackoverflow question here
Try inserting these lines before GetProcessByName
if (Console.KeyAvailable)
{
if (ConsoleKey.Pause == Console.ReadKey().Key)
continue;
}

How to break a loop with user input?

I want to break or pause a do/while loop if a user presses a key in the console. I have tried ReadLine or ReadKey but then my program stops and it is waiting for input, but I only want my program to stop after user input.
My code:
do
{
//do some code until user input
Console.WriteLine("for settings: Press 's'");
ConsoleKeyInfo cki;
cki = Console.ReadKey(); // here the program stops and waits for input but I don't want it
if (cki.Key.ToString() == "S")
{
Console.WriteLine("SETTINGS");
}
} while (true);
Check out Console.KeyAvailable this will be true when a user presses a key. When it is true then you can do Console.ReadKey()
You won't be able to have your program do that easily, that is actually doing 2 things at once 1) waiting on input (what readline/readkey does) and 2) continuing the work at the same time.
You could do this with multithreading by launching having your logic executing on one threat and the waiting on user input on another thread, then communicating between threads when user input happens but based on your question this is probably a too compelx answer, i will gladly write a sample but i think it is more likely to confuse than to help.

better end on keypress

I am writing a console app and found this method to end a loop on a keypress:
while (!Console.KeyAvailable){//do stuff}
It works, but it echos the key that was pressed back to the prompt. Is there a better method?
edit:
To clarify more, the loop runs and if hit the letter j the loop ends and the program exits. However, I get the following output at the prompt:
C:\>j
If you want to exit from a loop after a particular key is pressed, then instead of Console.KeyAvailable you can use the Console.ReadKey() function and check the return type of this function as an exit condition.
Here is the implementation.
while (true) {
var keyPressed = Console.ReadKey(true);
if (keyPressed.KeyChar == 'j') break;
//do something
Console.WriteLine("Key pressed: " + keyPressed.KeyChar);
}
For more details: C# Console - hide the input from console window while typing

trapping a key before it gets to the Console

THE SETTING:
A Console program, in .net
I am using readkey in a loop, which rewrites to the same line on the screen (Console.setCursorPosition)
however, if I type Enter, the Console pushes the text upwards, which is the usual command line behaviour.
THE QUESTION:
Is it possible to trap a key press (that Enter), so that my program will get the key, but the Console does not?
The environment is Linux, with Mono (and the program is supposed to be cross platform). so low level windows driver intercepting is not an option.
PS: I know the method of clearing and redrawing everything. I would like to know if my question is possible.
Thank you for any information
after modifying code found here https://stackoverflow.com/a/8898251/1951298 I came to something that may help you, you see that when user pushes Enter the cursor doesn't increment, and nothing is written into console
ConsoleKeyInfo keyinfo;
int left, top=0;
do
{
left = Console.CursorLeft;
top = Console.CursorTop;
keyinfo = Console.ReadKey(true);
if(keyinfo.Key.ToString().Equals("Enter"))
Console.SetCursorPosition(left,top-1);
else
Console.WriteLine(keyinfo.Key + " was pressed");
}
while (keyinfo.Key != ConsoleKey.X);
Console.ReadKey(true) should read the key but not show it.
You should intercept the key press. MSDN Documentation
var PressedKey = Console.ReadKey(true)

Disabling input in C# Console until certain task is completed

I'm working on a little part of my program, handling the input, basically I have this little code:
bool Done = false;
while (!Done)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
//Action
}
}
The main problem with this is that the code will handle the ReadKey even between actions.
So if you have a menu where you can press keys and then it would say "you pressed: x" if you press any buttons while it shows you this message, the ReadKey already gets that new key.
So I want to block any further input until the user sees the menu again.
Not so sure this make sense, personally I like it when keystrokes don't disappear and I can type ahead. But you can flush the keyboard buffer like this:
while (!Done)
{
while (Console.KeyAvailable) Console.ReadKey(true);
ConsoleKeyInfo key = Console.ReadKey(true);
// etc..
}
You can not block input,
Even if you do not process it, it goes to the keyboard buffer.
You can simply stop getting them out of the buffer though.

Categories