繁体   English   中英

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

[英]How to write back to command line from c# program

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

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

除了代码,您还需要更改以下内容:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM