C0d1ng
C0d1ng

Reputation: 451

c# console storing typed text while loop is running?

Ok, so in my c# console application it starts somewhat similar to this

static void Main()
{
    OpenLoginForm();
}

OpenLoginForm()
{
    while(true)
    {
        //This breaks when user has logged in
    }
}

Anything that a user tries to type in the console WILL NOT output to the console UNTIL OpenLoginForm() has stopped running, the problem is, that when OpenLoginForm() STOPS running any text that the user tried to type into the console BEFORE OpenLoginForm() stopped running will output to the console AFTER OpenLoginForm() has stopped running even though while OpenLoginForm() was running the text DIDN'T output to the console. I need it so even if a user types in the console when OpenLoginForm() is running, the text the user tries to input will not output even when OpenLoginForm() stops running.

Here is a gif that shows me typing into the console when OpenLoginForm() is running, but you will be able to see when OpenLoginForm() stops running the text i tried to type then gets outputted even though this is what I'm trying to prevent. enter image description here

Hopefully i worded this question in a way some of you will understand, I'm new to c# (I'm sure you can tell).

Upvotes: 0

Views: 160

Answers (2)

Travis
Travis

Reputation: 1095

The thing is that everything here is being run on the same thread, so while the console window is open, nothing appears in the console. However, the console input buffer is still filling with keystrokes.

You should be able to address this by clearing the input buffer, as described in this question. It is based on using Console.ReadKey(true) which (somewhat counter-intuitively) causes the input key to not appear in the console window (false will allow to appear). You then just throw the input away.

Here's the MSDN article on Console.ReadKey(bool).

Upvotes: 2

Shon
Shon

Reputation: 486

This is an issue with threads. Basically the input buffer for the console is active wgile the output is disabled. When you box closes then the output buffer for the console is turned on and the input buffer is flushed to the output buffer. The simplest solution is to use multiple threads. The main thread which will run the console and a child thread which will run the login box. Also as a child if the console is closed it will close the child

Upvotes: 1

Related Questions