Winforms中Console.WriteLine()的用途是什么

10 c# console-application winforms

我曾经看过一个winform应用程序的源代码,代码有一个Console.WriteLine();.我问了原因,我被告知这是出于调试目的.

请问Console.WriteLine();a 的本质是winform什么以及它执行什么操作,因为当我尝试使用它时,它从未写过任何东西.

Hae*_*ian 14

它写入控制台.

最终用户不会看到它,说实话,将其放入正确的日志会更加清晰,但如果您通过VS运行它,则会填充控制台窗口.

  • 没关系,我想我找到了它;它称为输出(在“视图”选项卡下方)。 (2认同)

Ant*_*ell 6

Winforms只是显示窗口的控制台应用程序.您可以将调试信息定向到控制台应用程序.

正如您在下面的示例中所看到的,有一个命令可以附加父窗口,然后将信息提供给它.

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() );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是此示例的资源:http://www.csharp411.com/console-output-from-winforms-application/

  • "Winforms只是显示窗口的控制台应用程序" - 我不同意,甚至坚定.Windows中有两种应用程序:创建窗口的GUI应用程序和在字符模式控制台中运行的(非GUI)控制台应用程序,最着名的是cmd.exe和Powershell.控制台应用程序*可以通过调用适当的API来创建窗口,GUI应用程序*可以像控制台应用程序一样读取和写入stdin和stdout,但这并不意味着它们不是两个完全不同的动物.是的,正如其他人所指出的那样,GUI应用程序中的Console.WriteLine()不是推荐的方式. (2认同)
  • 你的第一句话绝对不是真的。GUI(WINDOWS子系统)和控制台(CONSOLE子系统)应用程序有不同的子系统。 (2认同)