可能重复:
How to Run a C# console application with the console hidden.
通过类库如何在后台运行控制台应用程序来执行任务,然后告诉我的方法完成处理?
答案 0 :(得分: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 :(得分: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
}
答案 2 :(得分: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));
}
}
}