I have console application that can turn winform with richtextbox. I want to redirect console and that richtextbox to each other. So whenever I write to them text will copy to another. My problem is when I'm waiting for ReadLine. I would like to react to first ReadLine. This is my code:
class ConsoleFormReDirectWriter : TextWriter
{
TextWriter t;
RichTextBox r;
public ConsoleFormReDirectWriter(TextWriter TextWriter, RichTextBox FormOut)
{
t = TextWriter;
r = FormOut;
}
public override void Write(char value)
{
t.Write(value);
RichTextBoxExtensions.AppendText(r, value +"", Color.White);
}
public override void WriteLine(string line)
{
t.WriteLine(line);
RichTextBoxExtensions.AppendText(r, line+"\n", Color.White);
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
class ConsoleFormReDirectReader : TextReader
{
Queue<string> ReadLineQ = new Queue<string>();
public void AddToReadLineQueue(string s)
{
ReadLineQ.Enqueue(s);
}
public override string ReadLine()
{
string line = "";
while (true)
{
if (ReadLineQ.Count != 0) { line = ReadLineQ.Dequeue(); break; }
}
return line;
}
}
Then im handling press enter event on richtext box and apending queue by currentLine. I dont know how to make something similar with console.
or is there a better method of doing same?
PS: i can make new thread that will be asking console for readline in infinite loop, and when readline return something than i can append the queue. But that seems very unefective.
After a while i found semi solution. I used Console.readline with timeout and now I have my Readline:
public override string ReadLine()
{
bool toConsole=false, toUI=false;
string line = "";
while (true)
{
if (ReadLineQ.Count != 0)
{ line = ReadLineQ.Dequeue();
toConsole = true;
break;
}
try
{
line = DelayReader.ReadLine(50);
}
catch(TimeoutException) { continue; }
toUI = true;
break;
}
if (toConsole) t.WriteLine(line);
if (toUI) RichTextBoxExtensions.AppendText(r, line + "\n", Color.White);
return line;
}
And Console.Readline with delay i foun here: ReadLine(delay)