Reputation: 269
Ever wondered how you could write out to a separate console window from your Windows application rather than writing to a log file? You might need to do that for a number of reasons – mostly related to debugging.
Upvotes: 6
Views: 19983
Reputation: 731
Here's how you do it: Predefined APIs are available in kernel32.dll that will allow you to write to a console. The following shows a sample usage of the feature.
private void button1_Click(object sender, EventArgs e)
{
new Thread(new ThreadStart(delegate()
{
AllocConsole();
for (uint i = 0; i < 1000000; ++i)
{
Console.WriteLine("Hello " + i);
}
FreeConsole();
})).Start();
}
You’ll need to import the AllocConsole and FreeConsole API from kernel32.dll.
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
public static extern bool FreeConsole();
And you can always make it Conditional if you want to use it only while debugging.
private void button1_Click(object sender, EventArgs e)
{
new Thread(new ThreadStart(delegate()
{
AllocateConsole();
for (uint i = 0; i < 1000000; ++i)
{
Console.WriteLine("Hello " + i);
}
DeallocateConsole();
})).Start();
}
[Conditional("DEBUG")]
private void AllocateConsole()
{
AllocConsole();
}
[Conditional("DEBUG")]
private void DeallocateConsole()
{
FreeConsole();
}
Upvotes: 4
Reputation: 14618
If you have console application then do
System.Console.WriteLine("What ever you want");
If you have form application, you need to create console first:
http://www.csharp411.com/console-output-from-winforms-application/
Upvotes: 3
Reputation: 437326
To do this programmatically, you can PInvoke the appropriate Win32 console functions (e.g. AllocConsole
to create your own or AttachConsole
to use another process's) from within your own code. This way you have the best control over what actually happens.
If you are OK with having a console window open alongside your other UI for the full lifetime of your process, you can simply change the project properties from within Visual Studio and choose "Console Application", simple as that:
Upvotes: 13
Reputation: 3439
You can console output from a Windows Forms application using kernel32.dll. For complete detail check this article.
Upvotes: 2