Unfortunately, the answer is you can't hook the console's WndProc because it's in a separate, security-controlled process. Spy++ can hook other processes' WndProcs to read window messages, and Spy++ can't even read console window messages. Even if you could work around the security issue, C# cannot be used to hook another process.
I'm having the exact same race condition on resize. It's worse on Windows 10 because resizing the window reflows the text and changes the buffer width as well as the window width. Console.BufferWidth
, Console.BufferHeight
and family are non-atomic and will throw both managed and unmanaged errors if you use them while the window is being resized.
You can definitely find out about resizes after the fact by Reading Input Buffer Events but that won't solve your problem. You'll still have concurrency issues. Since that's not a hook, you can't make the resize wait for you to finish the Console
class's non-atomic buffer/window size operations.
I think the only option to deal with the race condition is a retry loop, and that is what I will use.
while (true) try
{
// Read and write the buffer size/location and window size/location and cursor position,
// but be aware it will be rudely interrupted if the console is resized by the user.
}
catch (IOException) { }
catch (ArgumentOutOfRangeException) { }
WndProc
is in a separate process and is not going to be hookable. Spy++ can't even hook Console window messages because of desktop security. baboulaf's answer is wasteful and inaccurate. I think the right way to do it must be the Console Input Buffer which Blorgbeard also found. – Shien