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

前端 未结 4 1385
终归单人心
终归单人心 2021-02-08 11:12

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

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-08 11:44

    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/

提交回复
热议问题