C#hybird Winforms/console应用程序返回cmd提示符

本文关键字:返回 cmd 提示符 应用程序 console Winforms C#hybird | 更新日期: 2023-09-27 18:30:08

我看到了许多针对C#的混合gui/cli应用程序的例子。我已经实现了这样一个应用程序,但我很难弄清楚如何防止.exe在命令行上运行时不能立即返回到提示。

    //defines for commandline output     
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);
    private const int ATTACH_PARENT_PROCESS = -1;
    [STAThreadAttribute]
    static void Main(string[] args)
    {
        // load cli
        // redirect console output to parent process;         
        // must be before any calls to Console.WriteLine()         
        AttachConsole(ATTACH_PARENT_PROCESS);
        if (args.Length == 0)
        {
            //loads gui
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new form_Main());
        }
        else
        {
            cli_main cli = new cli_main();
            cli.start_cli(args);
            Console.WriteLine("finished");
            System.Windows.Forms.SendKeys.SendWait("{ENTER}");
            Application.Exit();
        }
    }

我得到以下输出

C:'Users'john'Documents'Visual Studio 2010'Projects'test'test'test'bin'Debug>test.exe -param1 test 
-param2 test2
C:'Users'john'Documents'Visual Studio 2010'Projects'test'test'test'bin'Debug>Output was successful. File saved as: c:'test'test.html
finished

"finished"一行是当我知道我已经到达主代码的末尾时输出的字符串。。。这在Winforms中运行良好,我的项目是Winforms,我最初是作为gui启动的,但现在我正在尝试使其混合gui/cli

它似乎正在运行我在调试中看到的主代码和线程,并创建了我的最终输出文件。。。

我只是很困惑,当从cmd行执行.exe时,如何保持它的参数,不返回命令提示符??让它用闪烁的光标等待,然后输出关于html文件的行,然后输出"finished"行,最后返回命令提示符。

我试过很多方法,比如删除

System.Windows.Forms.SendKeys.SendWait("{ENTER}");
Application.Exit();

而不是使用Application.Exit();使用Environment.Exit(0);,但它总是立即返回命令提示符,我也尝试在行后休眠5秒

cli.start_cli(args);

但这也不起作用,我想我不明白它怎么能立即返回命令提示符,而且它甚至还没有到达行

Console.WriteLine("finished");

C#hybird Winforms/console应用程序返回cmd提示符

FWIW,我也尝试了第一种方法。我最终只是用隐藏了控制台窗口

IntPtr handle = GetConsoleWindow();
if (handle != IntPtr.Zero)
{
    ShowWindow(handle, 0);  // 0=SW_HIDE
}

这会完全隐藏窗口,甚至从任务栏中也会隐藏。它会闪烁一秒钟,但在我的情况下这是可以接受的