JonH
JonH

Reputation: 821

Reading from and writing to the Console at the same time in .NET

I'm building a .NET 4.0 console application which is constantly (that is, every few seconds usually) writing out to the console. It's a multi-threaded app and different threads write to the console at different times.

The problem is that I want to accept user input while all this is happening. The user input could occur at any time.

I tried tried two different methods, and neither worked very well.

  1. I tried using a separate thread for reading by looking forConsole.KeyAvailable. This "worked" but was really confusing because strings were being written to output as you were trying to input. This made the cursor move around while typing and was disorienting.

  2. I tried using Console.SetCursorPosition to split the console into two "panes". Output up top and input down below. This also worked but I have to call Console.Clear() after drawing the screen each time. This was very slow and caused mad screen flickering.

It seems like my only other option is to write a Windows Forms app or WPF app to emulate the console. This seems ridiculous since the only thing I want to do is to accept spontaneous user input.

My google-fu did not turn up any valid console replacements or anyone who had build a .NET app that simulated the console....

Am I stuck here?

Upvotes: 0

Views: 246

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 133995

It's possible, but difficult. It's not something that I'd recommend trying. You have to create a custom TextWriter that you set (Console.SetOut). That TextWriter leaves one or two lines at the bottom of the console window for you to use for writing. You end up having to scroll the window yourself, position the cursor yourself, etc. You also have to worry about wrapping lines and all that rot. It's ... maddening.

If you want to play with it, you'll need intimate knowledge of the Console API, and a .NET wrapper for it. I published a .NET wrapper a few years ago. You could do all this with that wrapper. You can download the wrapper from http://mischel.com/pubs/consoledotnet.zip

I wrote three articles about it, two of which are still available. See

http://www.devsource.com/c/a/Using-VS/Working-with-Console-Screen-Buffers-in-NET/

and

http://www.devsource.com/c/a/Using-VS/Console-Input-in-NET/

Upvotes: 1

Nikolay
Nikolay

Reputation: 3828

How about just to have 2 console windows? One for input and secound for output. You can create console windows with WinApi.

Upvotes: 0

Related Questions