我创建了一个Windows窗体解决方案,在类的构造函数中调用了以下代码:
Console.WriteLine("constructer called")
但是我只看到了窗体,没有看到控制台输出。那么输出结果在哪里呢?
我创建了一个Windows窗体解决方案,在类的构造函数中调用了以下代码:
Console.WriteLine("constructer called")
但是我只看到了窗体,没有看到控制台输出。那么输出结果在哪里呢?
你还应该考虑使用Debug.WriteLine,这可能是你正在寻找的。这些语句会被写入应用程序的跟踪侦听器,并且可以在Visual Studio的输出窗口中查看。
Debug.WriteLine("constructor fired");
如果你在Visual Studio中运行应用程序,你可以在输出窗口中查看控制台输出。
调试 -> 窗口 -> 输出
需要注意的是,从WinForms应用程序输出诊断数据的首选方式是使用System.Diagnostics.Debug.WriteLine
或System.Diagnostics.Trace.WriteLine
,因为它们更可配置,可以决定输出的方式和位置。
就像其他答案所述,System.Diagnostics.Debug.WriteLine
是调试信息的正确调用。但是回答你的问题:
从Windows窗体应用程序中,您可以按如下方式调用控制台窗口进行交互:
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();
有时候,我会使用这个方法来打开命令提示符,而不是打开应用程序窗口,当给定某些开关时。
如果有人需要更多的想法,请参考这个类似的问题:
什么是Winforms中Console.WriteLine()的作用