As you might see, your output goes to Visual Studio console, not opened one. To fix that issue you need to reopen console output stream:
if (AllocConsole())
{
var outHandle = CreateFile("CONOUT$",
(uint)(FileConsts.FILE_GENERIC_WRITE | FileConsts.FILE_GENERIC_READ),
(uint)(FileConsts.FILE_SHARE_WRITE | FileConsts.FILE_SHARE_READ),
0,
FileConsts.OPEN_EXISTING,
FileConsts.FILE_ATTRIBUTE_NORMAL, 0);
var inHandle = CreateFile("CONIN$",
(uint)(FileConsts.FILE_GENERIC_WRITE | FileConsts.FILE_GENERIC_READ),
(uint)(FileConsts.FILE_SHARE_WRITE | FileConsts.FILE_SHARE_READ),
0,
FileConsts.OPEN_EXISTING,
FileConsts.FILE_ATTRIBUTE_NORMAL, 0);
if (!SetStdHandle(STD_OUTPUT_HANDLE, outHandle))
throw new Exception("Can't set std handle");
if (!SetStdHandle(STD_INPUT_HANDLE, inHandle))
throw new Exception("Can't set std handle");
//Just for handle .Dispose();
var fileStream = new FileStream(new SafeFileHandle(outHandle, true), FileAccess.Write);
var fileStreamRead = new FileStream(new SafeFileHandle(inHandle, true), FileAccess.Read);
ConsoleKey read;
while ((read = Console.ReadKey().Key) != ConsoleKey.Escape)
{
Console.WriteLine($"Printed {read}");
}
Console.WriteLine("Escape Pressed, exiting");
SetStdHandle(STD_INPUT_HANDLE, IntPtr.Zero);
SetStdHandle(STD_OUTPUT_HANDLE, IntPtr.Zero);
fileStream.Dispose();
fileStreamRead.Dispose();
FreeConsole();
}
Note, that new FileStream("CONOUT$", ...)
and Console.OpenStandardInput()
won't work.
I've just tested it with Windows.Forms application. Console.ReadKey works correctly for me.
Create file and constants is from kernel32.dll