如何从C#程序写回命令行(How to write back to command line fro

2019-10-29 11:08发布

接受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());
        }
    }
}

“呦!” 出现在新的控制台窗口,但我想它的命令接口

Answer 1:

除了你的代码,您需要更改如下:

1)设置项目类型Console Application在项目设置页面。 你WinForms预期,如果不提供命令行PARAMS“模式”运行。

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());
    }                
}


文章来源: How to write back to command line from c# program