I have some screens making some data queries that might take a long time. My db layer already puts the query strings to the console (I can see them in the output window when debugging). I just want to have a window the user can open to see the same thing if they grow impatient.
Any suggestions on a quick way to do this?
Press CTRL + F5 to see your output. This will wait the console screen until you press any key. Save this answer.
Press F11 . Visual Studio calls the Console.
The Command window is used to execute commands or aliases directly in the Visual Studio integrated development environment (IDE). You can execute both menu commands and commands that do not appear on any menu. To display the Command window, choose Other Windows from the View menu, and select Command Window.
Right click your project in the solution explorer and select properties. Then, under the "Application" tab change the "Output type" of your project from “Console Application” to “Windows Application.” Save this answer.
If you redirect the Console.Out
to an instance of a StringWriter
, you can then get the text that has been written to the console:
StringWriter writer = new StringWriter();
Console.SetOut(writer);
StringBuilder consoleOut = writer.GetStringBuilder();
string text = consoleOut.ToString();
If you do this within a new Form
, you can then poll at an interval to get the text that has been written to the console so far and put its value into a TextBox
. A crude example:
public MyForm()
{
InitializeComponent();
StringWriter writer = new StringWriter();
Console.SetOut(writer);
Timer timer = new Timer();
timer.Tick += (o, s) => textBox.Text = writer.GetStringBuilder().ToString();
timer.Interval = 500;
timer.Start();
}
A few things to be careful with:
StringWriter
is disposable, so technically you need to dispose of it when done (although in reality its Dispose()
method does nothing so not really a big issue).StringWriter
keeps an internal StringBuilder
containing all of the text written to it so far. This will only ever get bigger over time, so the longer your application runs, the more memory it will consume. You could put some checks in to clear it out periodically when it reaches a certain size.Console.Out
back to its original value when you close your form, otherwise you will not be able to print messages to the console again.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With