How do I show a console output/window in a forms application?

Wil picture Wil · Dec 6, 2010 · Viewed 330.2k times · Source

To get stuck in straight away, a very basic example:

using System;
using System.Windows.Forms;

class test
{ 
    static void Main()
    { 
        Console.WriteLine("test");
        MessageBox.Show("test");
    }
}

If I compile this with default options (using csc at command line), as expected, it will compile to a console application. Also, because I imported System.Windows.Forms, it will also show a message box.

Now, if I use the option /target:winexe, which I think is the same as choosing Windows Application from within project options, as expected I will only see the Message Box and no console output.

(In fact, the moment it is launched from command line, I can issue the next command before the application has even completed).

So, my question is - I know that you can have "windows"/forms output from a console application, but is there anyway to show the console from a Windows application?

Answer

wizzardz picture wizzardz · Dec 6, 2010

this one should work.

using System.Runtime.InteropServices;

private void Form1_Load(object sender, EventArgs e)
{
    AllocConsole();
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();