如何从 C# 程序写回命令行

接受 CLI 参数的 Winform 应用程序在运行时会打开新的控制台窗口,但我希望它在 CLI 中运行并返回任何 Console.WriteLine()


这就是我如何分离 GUI 和控制台


static class program{

    [STAThread]

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]

    private static extern bool AllocConsole();


    static void Main(string[] args){

        if (args.Length > 0)

        {

            AllocConsole();

            Console.WriteLine("Yo!");

            Console.ReadKey();

        }

        else

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new someForm());

        }

    }

}

“哟!” 出现在新的控制台窗口中,但我希望它出现在命令界面中


ABOUTYOU
浏览 65回答 1
1回答

慕姐4208626

除了您的代码之外,您还需要更改以下内容:1) 在项目设置页面中将项目类型设置为Console Application。WinForms如果未提供命令行参数,您的“模式”将按预期运行。2) 删除对 的调用AllocConsole。3) 如果您运行的是 WinForms 模式,请隐藏控制台窗口。这是完整的代码:[System.Runtime.InteropServices.DllImport("kernel32.dll")]static extern IntPtr GetConsoleWindow();[System.Runtime.InteropServices.DllImport("user32.dll")]static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);[STAThread]static void Main(string [] args){    if (args.Length > 0)    {                      Console.WriteLine("Yo!");        Console.ReadKey();    }    else    {        ShowWindow(GetConsoleWindow(), 0);        Application.EnableVisualStyles();        Application.SetCompatibleTextRenderingDefault(false);        Application.Run(new Form1());    }                }
打开App,查看更多内容
随时随地看视频慕课网APP