简体   繁体   English

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

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

Winform app that accepts CLI arguments opens new console window when run, but i want it to run in the CLI instead and return any Console.WriteLine()'s there 接受CLI参数的Winform应用程序在运行时会打开新的控制台窗口,但我希望它改为在CLI中运行并返回任何Console.WriteLine()

This is how i split out the GUI and the console 这就是我拆分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());
        }
    }
}

"Yo!" “ Y!” appears in new console window, but i want it in the command interface 出现在新的控制台窗口中,但我希望它在命令界面中

In addition to your code, you need to change following: 除了代码,您还需要更改以下内容:

1) Set your project type to Console Application in project settings page. 1)在项目设置页面中,将项目类型设置为Console Application Your WinForms "mode" will run as expected if command line params are not supplied. 如果未提供命令行参数,则WinForms “模式”将按预期运行。

2) Remove the call to AllocConsole . 2)删除对AllocConsole的呼叫。

3) Hide the Console Window in case your are running the WinForms mode. 3)如果您正在运行WinForms模式,请隐藏控制台窗口。

Here is the complete code: 这是完整的代码:

[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