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")]
publicstaticexternBoolean AllocConsole();

[DllImport("kernel32.dll")]
publicstaticexternBoolean FreeConsole();

[DllImport("kernel32.dll")]
publicstaticexternIntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll")]
publicstaticexternbool SetConsoleTitle(String lpConsoleTitle);

[DllImport("kernel32.dll", SetLastError = true)]
publicstaticexternbool SetConsoleTextAttribute(IntPtr hConsoleOutput, CharacterAttributes wAttributes);

//And here is the enumeration CharacterAttributes

publicenumCharacterAttributes
{
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
}

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

privatevoid 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.

privatevoid 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
/ 0 نظر / 36 بازدید