在C#中执行控制台应用程序?

4

你所说的控制台应用程序是指DOS窗口可执行文件吗? - Brad Christie
你想让它异步返回还是等待应用程序完成? - Joe
3
你应该尽量将更多人给你的答案标记为“已采纳”。这有助于其他遇到相同问题的人,并且可以给那些帮助你的人应有的认可。 - Will Vousden
3个回答

5
您可以使用 Process 类来实现此功能。
以下是一个示例:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "your application path";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();

还有一个HasExited属性,用于检查进程是否已完成。

您可以像这样使用它:

if (p.HasExited)...

或者您可以将EventHandler绑定到Exited事件。


1

如果您可以等待应用程序运行完成,请使用proc.WaitForExit(),就像Shekhar的答案中所示。如果您希望它在后台运行而不等待,请使用Exited事件。

Process proc =
    new Process
    {
        StartInfo =
        {
            FileName = Application.StartupPath +  @"your app name",
            Arguments = "your arguments"
        }
    };

proc.Exited += ProcessExitedHandler;

proc.Start();

完成后,您可以检查错误代码:

if (proc.ExitCode == 1)
{
    // successful
}
else
{
    // something else
}

1
我在这里冒险猜测,您的意思是完全隐藏控制台应用程序窗口。
如果是这样,您可以通过一些P/Invoking来实现。
我撒谎了。我最初发布的代码只是禁用托盘中的“X”按钮。对于造成的困惑,我很抱歉...
WinForms.ShowWindow(consoleWindow, NativeConstants.SW_HIDE)

    [DllImport("user32.dll")]
    public static extern Boolean ShowWindow(IntPtr hWnd, Int32 show);

这里的 P/Invoke 语句:

    /// <summary>
    ///     The EnableMenuItem function enables, disables, or grays the specified menu item.
    /// </summary>
    /// <param name="hMenu"></param>
    /// <param name="uIDEnableItem"></param>
    /// <param name="uEnable"></param>
    /// <returns></returns>
    [DllImport("user32.dll")]
    public static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();

    /// <summary>
    ///     The GetSystemMenu function allows the application to access the window menu (also known as the system menu or the control menu) for copying and modifying.
    /// </summary>
    /// <param name="hWnd"></param>
    /// <param name="bRevert"></param>
    /// <returns></returns>
    [DllImport("user32.dll")]
    public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

原始代码

    private static IntPtr hWndConsole = IntPtr.Zero;
    private static IntPtr hWndMenu = IntPtr.Zero;

    public static void Main(string[] args)
    {
        hWndConsole = WinForms.GetConsoleWindow();
        if (hWndConsole != IntPtr.Zero)
        {
            hWndMenu = WinForms.GetSystemMenu(hWndConsole, false);

            if (hWndMenu != IntPtr.Zero)
            {
                WinForms.EnableMenuItem(hWndMenu, NativeConstants.SC_CLOSE, (uint)(NativeConstants.MF_GRAYED));
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接