6

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.

4
  • Can you specify what you mean by "Windows Application"? A Windows Forms application, or something else? Commented Mar 30, 2012 at 12:38
  • Change your project type from WinForms to Console App. Now you have both. Forms+Console Commented Mar 30, 2012 at 12:40
  • 2
    Not really, not when I can just output to a textBox or memo component on a GUI form. Commented Mar 30, 2012 at 12:41
  • 1
    actual solution : nerdyhearn.com/blog/157 Commented Feb 24, 2014 at 9:08

4 Answers 4

13

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:

VS Project settings

Sign up to request clarification or add additional context in comments.

1 Comment

its crazy how Microsoft makes so complex what is so pure and simple in Unix world.
4

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(); } 

Comments

3

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/

Comments

2

You can console output from a Windows Forms application using kernel32.dll. For complete detail check this article.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.