Development World

New Development Technologies , Computer Last News , Tips & Tricks , UI , CSS , HTML , ASP , C# , .net Framework , Patterns & Practices & etc

Console window for a Windows application in .NET

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 = 0×0001,
FOREGROUND_GREEN = 0×0002,
FOREGROUND_RED = 0×0004,
FOREGROUND_INTENSITY = 0×0008,
BACKGROUND_BLUE = 0×0010,
BACKGROUND_GREEN = 0×0020,
BACKGROUND_RED = 0×0040,
BACKGROUND_INTENSITY = 0×0080,
COMMON_LVB_LEADING_BYTE = 0×0100,
COMMON_LVB_TRAILING_BYTE = 0×0200,
COMMON_LVB_GRID_HORIZONTAL = 0×0400,
COMMON_LVB_GRID_LVERTICAL = 0×0800,
COMMON_LVB_GRID_RVERTICAL = 0×1000,
COMMON_LVB_REVERSE_VIDEO = 0×4000,
COMMON_LVB_UNDERSCORE = 0×8000
}

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.


Reference : vaibhavgaikwad.wordpress.com