How to write to a console window from a Windows application?

Ever wondered how you could log out a separate console window from your Windows application instead of writing to a log file? You may need to do this for a number of reasons - mostly related to debugging.

+3


source to share


4 answers


To do this programmatically, you can PInvoke the appropriate Win32 console functions (for example AllocConsole

, to create your own or AttachConsole

to use another process) from your own code. That way, you have better control over what actually happens.

If you're ok with opening a console window along with another UI for the full lifetime of your process, you can simply change the project properties from Visual Studio and select Console Application, simple:



VS Project settings

+12


source


If you have a console application, do

System.Console.WriteLine("What ever you want");

      



If you have a form application, you need to create a console first:

http://www.csharp411.com/console-output-from-winforms-application/

+3


source


Here's how you do it: Predefined APIs are available in the kernel32.dll file, which will allow you to write to the console. Below is an example of using this function.

private void button1_Click(object sender, EventArgs e) 
{
     new Thread(new ThreadStart(delegate()
     {
        AllocConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        FreeConsole();
    })).Start();
}

      

You need to import API AllocConsole and FreeConsole from kernel32.dll file.

[DllImport("kernel32.dll")]
public static extern bool AllocConsole();

[DllImport("kernel32.dll")]
public static extern bool FreeConsole();

      

And you can always make it conditional if you only want to use it while debugging.

private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocateConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        DeallocateConsole();
    })).Start();
}


[Conditional("DEBUG")]
private void AllocateConsole()
{
    AllocConsole();
}

[Conditional("DEBUG")]
private void DeallocateConsole()
{
    FreeConsole();
}

      

+3


source


You can disable output from a Windows Forms application using kernel32.dll. For a full check of the details in this article .

+2


source







All Articles