小编典典

如何在表单应用程序中显示控制台输出/窗口?

c#

要立即陷入困境,这是一个非常基本的示例:

using System;
using System.Windows.Forms;

class test
{ 
    static void Main()
    { 
        Console.WriteLine("test");
        MessageBox.Show("test");
    }
}

如果按预期使用默认选项(在命令行使用csc)进行编译,它将编译为控制台应用程序。另外,由于我已导入System.Windows.Forms,因此它还会显示一个消息框。

现在,如果我使用option /target:winexe,我认为它与Windows Application从项目选项中进行选择相同,那么按预期,我只会看到消息框,而没有控制台输出。

(实际上,从命令行启动它之后,我可以在应用程序完成之前发出下一条命令)。

所以,我的问题是-我知道您可以从控制台应用程序中获取“ windows” /窗体输出,但是无论如何,还是可以从Windows应用程序中显示控制台吗?


阅读 319

收藏
2020-05-19

共1个答案

小编典典

这应该工作。

using System.Runtime.InteropServices;

private void Form1_Load(object sender, EventArgs e)
{
    AllocConsole();
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
2020-05-19