-1

当程序仍然在同一个控制台中工作时,我如何像在 Java 中一样重新启动我的 C# 控制台应用程序,而不创建新的控制台。

我试图启动新应用程序Process.UseShellExecute = false并从新创建的进程中终止当前进程,但我可以使用它从子进程中终止父进程。我试图在创建新进程后杀死当前进程,但它也不起作用。

4

1 回答 1

0

没有直接的方法可以做到这一点,但是您可以模拟这种行为:

  1. 将您的应用程序从控制台应用程序更改为 Windows 应用程序。
  2. 为您的应用程序的第一个实例创建一个控制台
  3. 启动应用程序的新实例并附加到步骤 2 中创建的控制台。
  4. 退出第一个实例。

重要的是不要忘记将应用程序类型更改为 Windows 应用程序。

以下代码将重新启动应用程序,直到您按下 Ctrl+C:

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();
    }
}
于 2012-07-02T21:06:11.733 回答