2011-02-10 41 views

回答

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)... 

,或者您可以将事件处理程序绑定到Exited事件。

1

如果您还在等待您的应用程序完成运行,请使用proc.WaitForExit(),就像在Shekhar的答案中一样。如果您希望它在后台运行而不是等待,请使用“退出”事件。

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