Console window for a Windows application in .NET

February 21, 2007

Have your ever felt the need to attach a Console window to your winform application?  If this is what you want, here is a article just for you.

I have not come across any possible way to show the Console window for a Windows application. So I tried my way with the help of Win32 API calls. Here is the list of APIs which will be needed:

[DllImport(“kernel32.dll”)]
public static extern Boolean AllocConsole();

[DllImport(“kernel32.dll”)]
public static extern Boolean FreeConsole();

[DllImport(“kernel32.dll”)]
public static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport(“kernel32.dll”)]
public static extern bool SetConsoleTitle(String lpConsoleTitle);

[DllImport(“kernel32.dll”, SetLastError = true)]
public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, CharacterAttributes wAttributes);

//And here is the enumeration CharacterAttributes

public enum CharacterAttributes
{
FOREGROUND_BLUE = 0x0001,
FOREGROUND_GREEN = 0x0002,
FOREGROUND_RED = 0x0004,
FOREGROUND_INTENSITY = 0x0008,
BACKGROUND_BLUE = 0x0010,
BACKGROUND_GREEN = 0x0020,
BACKGROUND_RED = 0x0040,
BACKGROUND_INTENSITY = 0x0080,
COMMON_LVB_LEADING_BYTE = 0x0100,
COMMON_LVB_TRAILING_BYTE = 0x0200,
COMMON_LVB_GRID_HORIZONTAL = 0x0400,
COMMON_LVB_GRID_LVERTICAL = 0x0800,
COMMON_LVB_GRID_RVERTICAL = 0x1000,
COMMON_LVB_REVERSE_VIDEO = 0x4000,
COMMON_LVB_UNDERSCORE = 0x8000
}

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

private void Form1_FormClosing(object sender, CancelEventArgs e)

    bool flag = FreeConsole();
}

//Put a button on the form and write the following code in to the Click event handler of the button.

private void button1_Click(object sender, EventArgs e)
{
    IntPtr hStdWin = GetStdHandle(-11);
   SetConsoleTitle(“My Console :)”);
   SetConsoleTextAttribute(hStdWin,CharacterAttributes.FOREGROUND_GREEN);
   Console.WriteLine(“Hi from Window application.”);

}

//code ends here

Check this out, and if this is not you expected, then put your comments.

-Bugs! 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: