1

我见过很多 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

“完成”行是当我知道我已经到达主代码末尾时输出的字符串......这在 Winforms 中运行良好,我的项目是 Winforms,我将它作为 gui 启动,但现在我正试图让它混合gui/cli

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

我只是对如何在从 cmd 行执行时保留 .exe 及其参数而不返回命令提示符感到困惑?让它等待闪烁的光标,然后输出关于 html 文件的行,然后输出“完成”行,最后返回命令提示符。

我已经尝试了很多东西,比如删除

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

而不是使用Application.Exit();useEnvironment.Exit(0);但它总是立即返回到命令提示符,我也尝试在该行之后进入睡眠 5 秒

cli.start_cli(args);

但这也不起作用,我想我不明白它如何立即返回命令提示符,而且它甚至没有这条线

Console.WriteLine("finished");
4

1 回答 1

6

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

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

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

于 2012-12-05T15:55:01.123 回答