How to write back to command line from c# program

百般思念 提交于 2019-12-11 16:07:32

问题


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

This is how i split out the GUI and the console

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!" appears in new console window, but i want it in the command interface


回答1:


In addition to your code, you need to change following:

1) Set your project type to Console Application in project settings page. Your WinForms "mode" will run as expected if command line params are not supplied.

2) Remove the call to AllocConsole.

3) Hide the Console Window in case your are running the WinForms mode.

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


来源:https://stackoverflow.com/questions/57624803/how-to-write-back-to-command-line-from-c-sharp-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!