2012-07-02 59 views
-1

當程序仍然在同一控制檯中工作,而無需創建新控制檯時,如何重新啓動我的C#控制檯應用程序(如Java)。重新啓動控制檯應用程序

我試圖用Process.UseShellExecute = false開始新的應用程序,並從新創建的當前進程中殺死,但我可以使用這個殺死父進程。我試圖在創建新程序後終止當前進程,但它也不起作用。

+0

儘量提供有關問題的詳細信息:直到你按下Ctrl + C

下面的代碼將重新啓動應用程序。 –

回答

0

還有就是要做到這一點沒有直接的方法,但你可以模擬這種行爲:

  1. 從控制檯應用程序應用程序更改爲Windows應用程序。
  2. 爲您的應用
  3. 的第一個實例創建一個控制檯
  4. 啓動應用程序的新實例,並重視在步驟2中
  5. 退出第一個實例創建的控制檯。

重要的是不要忘記將應用程序類型更改爲Windows應用程序。

using System; 
using System.Diagnostics; 
using System.Runtime.InteropServices; 
using System.Reflection; 

class Program 
{ 
    [DllImport("kernel32", SetLastError = true)] 
    static extern bool AllocConsole(); 

    [DllImport("kernel32.dll", SetLastError = true)] 
    static extern bool AttachConsole(uint dwProcessId); 

    const uint ATTACH_PARENT_PROCESS = 0x0ffffffff; 


    [STAThread] 
    static void Main(string[] args) 
    { 
     if (!AttachConsole(ATTACH_PARENT_PROCESS)) 
     { 
      AllocConsole(); 
     } 
     Console.WriteLine("This is process {0}, press a key to restart within the same console...", Process.GetCurrentProcess().Id); 
     Console.ReadKey(true); 

     // reboot application 
     var process = Process.Start(Assembly.GetExecutingAssembly().Location); 

     // wait till the new instance is ready, then exit 
     process.WaitForInputIdle(); 
    } 
} 
+0

單聲道,這將無法與單聲道,沒有辦法做到這一點,而不使用Windows內核庫? – Robert

+1

@Robert:你在非Windows平臺上嗎?如果是這樣,在哪個平臺上?請不要在您的問題中遺漏相關信息。 –

相關問題