windows form .. console.writeline() where is console?

C#.NetWinformsConsole Application

C# Problem Overview


I created a windows form solution and in the constructor of a class I called

Console.WriteLine("constructer called")

But I only got the form and not the console.. so where is the output?

C# Solutions


Solution 1 - C#

You should also consider using Debug.WriteLine, that's probably what you're looking for. These statements are written out the trace listeners for your application, and can be viewed in the Output Window of Visual Studio.

Debug.WriteLine("constructor fired");

Solution 2 - C#

In project settings set application type as Console. Then you will get console window and Windows form.

Solution 3 - C#

If you run your application in Visual Studio you can see the console output in the output window.

> Debug -> Windows -> Output

Note that the preferable way to output diagnostics data from a WinForms application is to use System.Diagnostics.Debug.WriteLine or System.Diagnostics.Trace.WriteLine as they are more configurable how and where you want the output.

Solution 4 - C#

As other answers have stated System.Diagnostics.Debug.WriteLine is the right call for debugging messages. But to answer your question:

From a Winforms application you can invoke a console window for interaction like this:

using System.Runtime.InteropServices;

...

void MyConsoleHandler()
{
    if (AllocConsole())
    {
        Console.Out.WriteLine("Input some text here: ");
		string UserInput = Console.In.ReadLine();

        FreeConsole();
    }
}


[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeConsole();

I sometimes use this to raise a command prompt instead of application windows when given certain switches on opening.

There's some more ideas in this similar question if anyone needs it:
https://stackoverflow.com/questions/18473902/what-is-the-purpose-of-console-writeline-in-winforms

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSmartestVEGAView Question on Stackoverflow
Solution 1 - C#BrandonZeiderView Answer on Stackoverflow
Solution 2 - C#Tomas VoracekView Answer on Stackoverflow
Solution 3 - C#Albin SunnanboView Answer on Stackoverflow
Solution 4 - C#noelicusView Answer on Stackoverflow