当程序仍然在同一个控制台中工作时,我如何像在 Java 中一样重新启动我的 C# 控制台应用程序,而不创建新的控制台。
我试图启动新应用程序Process.UseShellExecute = false
并从新创建的进程中终止当前进程,但我可以使用它从子进程中终止父进程。我试图在创建新进程后杀死当前进程,但它也不起作用。
当程序仍然在同一个控制台中工作时,我如何像在 Java 中一样重新启动我的 C# 控制台应用程序,而不创建新的控制台。
我试图启动新应用程序Process.UseShellExecute = false
并从新创建的进程中终止当前进程,但我可以使用它从子进程中终止父进程。我试图在创建新进程后杀死当前进程,但它也不起作用。
没有直接的方法可以做到这一点,但是您可以模拟这种行为:
重要的是不要忘记将应用程序类型更改为 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();
}
}