可能是重复问题:
如何隐藏C#控制台应用程序并运行。
通过一个类库,我如何在后台运行控制台应用程序来执行任务,然后告诉我的方法处理完成了?
可能是重复问题:
如何隐藏C#控制台应用程序并运行。
通过一个类库,我如何在后台运行控制台应用程序来执行任务,然后告诉我的方法处理完成了?
// 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事件。
如果您可以等待应用程序运行完成,请使用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
}
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));
}
}
}