How to use Console with a Winform App?
Let's say I have some code inside a Winform. I'd also like to output to Console like this:
Reader = command.ExecuteRea开发者_运维百科der();
while (Reader.Read())
{
string thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
thisrow += Reader.GetValue(i).ToString() + ",";
Console.WriteLine(thisrow);
}
connection.Close();
It doesn't crash but I can't see any console. Why ?
It goes to the Output window when you run this code in Visual Studio. It goes in the bit-bucket if you don't. It goes to a console window if you change the application type. Project + Properties, Application tab, Output type = "Console Application". Not exactly useful.
The output in fact DOES go to the "console" -- you just don't see the console window. I.e. if you tried to read the standard output of your program from another program, you would see all the data you print to the console. If you really want to see the console window, change your application to a Console Application. (You can still run forms and everything just like you would in a windows application.)
You won't see a console when you create a Windows (WinForm) application. It is generally recommended that you create a console application and then build your forms attached to that. The problem is that you must run the forms asynchronously to properly update your forms.
My suggestion would be to create a multi-line textbox and simply print to that. If you want it to look like a console, make the background black with white text, put the textbox into a form by itself.
You can use the Trace class and define your own TraceListener in the form of a console window of your own creation. There is lots of help out there; just google "custom tracelistener". Or you might find an existing freebie that does what you want.
If you want to see the console output, you could set your project to have both a console window as well as a visible form.
If you set the project to be a console application, a console window will appear. Then in your Main
method put:
public static void Main()
{
Application.Run(new MyForm());
}
This will leave the console window open, but start your form as well, so both are visible at the same time. Anything you output to the console will then then appear in the console window.
精彩评论