12

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

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

4

4 回答 4

14

它写入控制台。

最终用户不会看到它,老实说,将它放入适当的日志中会更干净,但是如果您通过 VS 运行它,则会填充控制台窗口。

于 2013-08-27T19:31:41.833 回答
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() );
        }
    }
}

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

于 2013-08-27T19:33:44.147 回答
3

您不会真正正常使用它,但如果您附加了 Console 或使用AllocConsole,它将像在任何其他控制台应用程序中一样运行,并且输出将在那里可见。

对于快速调试,我更喜欢,Debug.WriteLine但对于更健壮的解决方案,Trace类可能更可取。

于 2013-08-27T19:34:34.970 回答
2

Console除非重定向到说Output窗口,否则它不会执行任何操作。真的,他们应该Debug.WriteLine改用杠杆。

这样做的好处是在模式下Debug.WriteLine构建时它会被优化掉。Release

注意:正如 Brad Christie 和 Haedrian 所指出的,显然它实际上会在Console运行 Windows 窗体应用程序时写入 Visual Studio 中的窗口。你每天学习新的东西!

于 2013-08-27T19:31:37.930 回答