Clear Console Buffer - c#

I'm writing a sample console application in VS2008. Now I have a Console.WriteLine() method which displays output on the screen and then there is Console.ReadKey() which waits for the user to end the application.
If I press Enter while the Console.WriteLine() method is displaying then the application exits.
How can I clear the input buffer before the Console.ReadKey() method so that no matter how many times the user presses the Enter button while the data is being displayed, the Console.ReadKey() method should stop the application from exiting?

Unfortunately, there is no built-in method in Console class. But you can do this:
while(Console.KeyAvailable)
Console.ReadKey(false); // skips previous input chars
Console.ReadKey(); // reads a char
Use Console.ReadKey(true) if you don't want to print skipped chars.
Microsoft References
Console.KeyAvailable
Console.ReadKey(bool)

Related

Calling AllocConsole & FreeConsole multiple times and keep In- & Output functionality of Console object in C# .NET

OS: Windows 10 Enterprise 1703 64-bit
I cannot allocate and free a console more than once without loosing the Console.ReadKey() functionality in a windows form application.
This question is similiar to Exception when using console window in a form application but the answer is missing out on the Console.ReadKey() function.
The following code works for the first execution only. One receives a new console window and the user has to press any key. On the second execution the text is displayed as well but Console.ReadKey() throws a System.InvalidOperationException.
System.InvalidOperationException: 'Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.'
Left out the DllImport declarations within the static Win32Wrapper class for brevity.
Win32Wrapper.AllocConsole();
// set standard out handle to console window
var ConOut = Win32Wrapper.CreateFile(
"CONOUT$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_WRITE,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, ConOut);
// set stadard in handle to console window
var ConIn = Win32Wrapper.CreateFile(
"CONIN$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_READ,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, ConIn);
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
Console.WriteLine("Hello World!"); // works every time
Console.Read(); // works every time
Console.ReadKey(true); // second call: InvalidOperationException
Win32Wrapper.CloseHandle(ConIn)
Win32Wrapper.CloseHandle(ConOut)
return Win32Wrapper.FreeConsole();
I found a way to simulate the above behaviour by not destroying the console I created before but instead simply hiding and displaying it again.
if (FirstTime)
{
FirstTime = false;
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, HWND.Zero);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, HWND.Zero);
Win32Wrapper.AllocConsole(); // show implicitly
}
else
{
Console.Clear(); // clear => simulate new console
Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 5); // show (again)
}
Console.WriteLine("Hello World!");
Console.Read();
Console.ReadKey(true);
Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 0); // hide
Only the first function call allocates a new console further calls only show the already existing console again. All I need is a static variable to take track of it.

continuing program after entering integer user input c#

when i run my code, my console suddenly shuts off after a number is entered into the console.
int age;
Console.WriteLine("How old are you?");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are {0} years old", age);
can someone help me with this problem? I never get to see the end result because it just shuts off. there are no errors that pop up but it is getting quite frustrating.
Add Console.ReadLine() or Console.ReadKey() as your last line.
When the execution of the program is done, the console windows closes. You have to make a way for a program to keep running so the console window stays open. Usually, this is achieved by adding
Console.ReadKey();
or
Console.ReadLine();
in the end of your code. This way the console is waiting for your input and it stays open. As soon as you hit any key in keyboard (in case of Console.ReadKey()) or Enter key (in case of Console.ReadLine()), execution is done and the console window exits.

Check and get user input from terminal C#

I am trying to get user input from the terminal in C#, but I only want to ReadLine when the user starts typing. Basically the way I have it set up now is that I am in a while loop and I want to either check to see if I got messages or send them, but I don't want to get stuck trying to send one by calling ReadLine and waiting for the user to send a message if they have nothing to send at the moment. My code looks something like this:
While (true)
{
// If messages to be received
// Receive them
// Check to see if the user is typing input
if (Console.KeyAvailable)
{
string userInput = Console.ReadLine();
// Do stuff...
}
}
Basically what is happening is that it works completely fine, but the first letter that the user types does not show up in the terminal window, but it does get picked up by the ReadLine no problem. Is there anyway I can get this to work so that the user can see everything they are typing right away?
Thanks!
You can use Console.ReadKey(true); to read missing item, then read other parts with readline method append it to your input.

Keep console up to wait for response

I've got a console app. I prompt the user for input...my code does its thing and at the end tries to print the output back to the user.
Here's how I try to post back the output to the same console window so they can see the results:
Console.WriteLine( "Output: ");
Console.WriteLine(resultMessage);
Problem is my console closes before it shows the resultMessage.
You can use Console.ReadKey(true); it waits for any key press
When you're in VS, you can also press Ctrl and f5 to open your application outside of the debugger.
A consequence of doing so is that your window will stick around when your program is finished saying
Press any key to continue
One more Console.Read...
if (Debugger.IsAttached)
{
Console.Write("Press Enter to exit: ");
Console.ReadLine();
}
I think it will be better in case of using output redirection to file like
ConsoleApp.exe >results.txt
Use Console.ReadKey(); after the output is written to the console.

Console window keeps closing, even after I type in other statements

I am new to programming and as seems to be traditional I tried to create a "hello world" program in C#; however, as soon as I run the program it closes.
This is my code inside:
main()
console.writeline("hello world");
console.writeline("enter name");
console.writeline("where is the frikin console");
It's really annoying and I know it might be something simple for the additional users but how do I keep the window open.
Use Console.ReadLine(); or Console.ReadKey(); at the end of your program to wait for the return key or for any key.
You can build your program and run the exe from the command line, that will allow you to see the output.
If you want the program to remain running then adding the Read() statement is the traditional approach, as others have already said.
If you just want to see it in debugging and do not want or need the read statement then place a breakpoint at the end of the program during a debug session.
It's really quite simple.
After this line of code:
Console.WriteLine("where is the frikin console");
You need to add this:
Console.ReadLine();
That should work.
The reason the console closes is because you told it to write some stuff to the screen, after it has finished writing what you told it to write it simply closes itself all in the fraction of a second. if you add Console.ReadLine, the console will wait for you to input something before closing, like pressing a key on the keyboard.
Try adding Console.Read(). You need to pause execution somehow.
Console.WriteLine("hello world");
Console.WriteLine("enter name");
Console.WriteLine("where is the frikin console");
Console.ReadLine();
Console.ReadLine(); will close the console after you've hit (for example) enter.
Console.ReadKey(); will close the console after the next key-hit
You can read the console-contents with these methods,too
Console.WriteLine("hello world");
Console.WriteLine("enter name");
string name = Console.ReadLine();
Console.WriteLine("Your name is: " + name);
Console.ReadLine();
add below line at the end
Console.ReadLine();
You could use CTRL + F5 which will opens the command line and after execution of your code, it shows Press any key to continue.... This will be handy for you than adding few lines of code additionally.
Use
Console.ReadLine();
in the end of your code. You are having this problem because the program just write the message then it ends, that's why you can't see anything. By adding that line, you keep the program waiting something to be typed and you can read the message. After this, type something to end the program.
The window automatically closes after your program, you need to let it take some input, for example:
Add
Console.ReadLine();
Which takes a line of input (till "\n"). And your program will wait until somebody hit the return key (they can type anything and the program won't close: until you hit the return key. You can type in "hello world back what's up are you ok?" and nothing will happen.)
or
Console.ReadKey();
Which will take a character of input. This will make your program wait for the user to press any key and then closes.

Categories

Resources