通過一個類庫,我怎麼在後臺運行一個控制檯應用程序來執行任務,然後告訴我的方法對其做處理可能重複:
How to Run a C# console application with the console hidden.在c#中執行控制檯應用程序?
?
通過一個類庫,我怎麼在後臺運行一個控制檯應用程序來執行任務,然後告訴我的方法對其做處理可能重複:
How to Run a C# console application with the console hidden.在c#中執行控制檯應用程序?
?
您可以使用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事件。
如果您還在等待您的應用程序完成運行,請使用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
}
我的肢體走出去這裏,但我想你的意思完全隱藏控制檯應用程序窗口。
在這種情況下,您可以通過一些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));
}
}
}
並通過控制檯應用程序我假定你的意思DOS窗口中執行? – 2011-02-10 00:36:17