There is no straightforward way to do this, however you can simulate this behavior:
- Change your application from console application to Windows application.
- Create a console for the first instance of your application
- Start a new instance of your application and attach to the console created in step 2.
- Exit the first instance.
It is important not to forget to change the application type to Windows application.
The following code will restart the application until you press 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();
}
}