OS: Windows 10 Enterprise 1703 64-bit
I cannot allocate and free a console more than once without loosing the Console.ReadKey() functionality in a windows form application.
This question is similiar to Exception when using console window in a form application but the answer is missing out on the Console.ReadKey() function.
The following code works for the first execution only. One receives a new console window and the user has to press any key. On the second execution the text is displayed as well but Console.ReadKey() throws a System.InvalidOperationException.
System.InvalidOperationException: 'Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.'
Left out the DllImport declarations within the static Win32Wrapper class for brevity.
Win32Wrapper.AllocConsole();
// set standard out handle to console window
var ConOut = Win32Wrapper.CreateFile(
"CONOUT$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_WRITE,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, ConOut);
// set stadard in handle to console window
var ConIn = Win32Wrapper.CreateFile(
"CONIN$",
GenericAccessRight.GENERIC_READ | GenericAccessRight.GENERIC_WRITE,
ShareMode.FILE_SHARE_READ,
IntPtr.Zero,
CreationDisposition.OPEN_EXISTING,
0,
IntPtr.Zero
);
Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, ConIn);
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
Console.SetIn(new StreamReader(Console.OpenStandardInput()));
Console.WriteLine("Hello World!"); // works every time
Console.Read(); // works every time
Console.ReadKey(true); // second call: InvalidOperationException
Win32Wrapper.CloseHandle(ConIn)
Win32Wrapper.CloseHandle(ConOut)
return Win32Wrapper.FreeConsole();