What is the Purpose of Console.WriteLine() in Winf

2019-03-27 05:14发布

问题:

I once saw the source code of a winform application and the code had a Console.WriteLine();. I asked the reason for that and i was told that it was for debugging purposes.

Pls what is the essence of Console.WriteLine(); in a winform and what action does it perform because when i tried using it, it never wrote anything.

回答1:

It writes to the Console.

The end user won't see it, and to be honest its much cleaner to put it into a proper log, but if you run it through VS the Console window will populate.



回答2:

Winforms are just console apps that show windows. You can direct your debug info to the console app.

As you can see in the below example there is a command that attaches the parent window then pumps info to it.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MyWinFormsApp
{
    static class Program
    {
        [DllImport( "kernel32.dll" )]
        static extern bool AttachConsole( int dwProcessId );
        private const int ATTACH_PARENT_PROCESS = -1;

        [STAThread]
        static void Main( string[] args )
        {
            // redirect console output to parent process;
            // must be before any calls to Console.WriteLine()
            AttachConsole( ATTACH_PARENT_PROCESS );

            // to demonstrate where the console output is going
            int argCount = args == null ? 0 : args.Length;
            Console.WriteLine( "nYou specified {0} arguments:", argCount );
            for (int i = 0; i < argCount; i++)
            {
                Console.WriteLine( "  {0}", args[i] );
            }

            // launch the WinForms application like normal
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );
            Application.Run( new Form1() );
        }
    }
}

Here is the resource for this example:http://www.csharp411.com/console-output-from-winforms-application/



回答3:

You wouldn't really use it normally but if you've attached a Console or use AllocConsole, it will function like in any other console application and the output will be visible there.

For quick debugging, I prefer Debug.WriteLine but for a more robust solution, the Trace class may be preferable.



回答4:

It wouldn't perform anything unless the Console was redirected to say the Output window. Really, they should be leveraging Debug.WriteLine instead.

The benefit of Debug.WriteLine is that it gets optimized away when building in Release mode.

NOTE: as pointed out by Brad Christie and Haedrian, apparently it will in fact write to the Console window in Visual Studio when running a Windows Forms application. You learn something new every day!