суббота, 2 октября 2010 г.

How to run Console in Windows Forms application

To be honest, it's quite easy to find out this with google, but I'd like to share a couple of useful tricks.

To open console window in Windows Forms application, write the following in Program.cs Main function:

[STAThread]
static void Main()
{
    AllocConsole();
    // .... the rest of the code, opening MainForm
}

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();


Console windows are usually need to be opened on debugging and tracing purposes. Note that if you didn't open Console window, everything you wrote using Console.WriteLine method would appear in Output tab in Visual Studio during debugging. So go to View > Output to open this tab and you will see your messages.

However, it's better to use more convenient Debug class from System.Diagnostics namespace and it's Debug.WriteLine method or another useful method Debug.Assert(), which checks weather some statement is true. This methods calls are not included into the final release build, because they are decorated with [ConditionalAttribute("DEBUG")] attribute, so you don't have to bother clearing up your code after debugging is finished. Console.WriteLine are not cleared out during release build, that's why it's not cool to use them.

You can also decorate your debugging methods with [ConditionalAttribute("DEBUG")] attribute or wrap debugging code in
#if DEBUG
#endif
language preprocessor directives.

You can find out even more great VisualStudio 2010 debugging tricks in a ScotGu's post.

Комментариев нет:

Отправить комментарий