So here I started wondering – shouldn’t it be possible to keep using Console.WriteLine and have the output appear in multiple places, by using some sort of special splitting or cloning pipe? A little research turned up nothing really explicit on what to do, but a few Windows functions which look they could feature somewhere in a solution:
GetStdHandle, SetStdHandle, CreatePipe, CreateFile.
So where do we get started?
Part 1: Interception
By reading about SetStdHandle, GetStdHandle, and CreateFile with special “CONIN$” and “CONOUT$” files we can see that there’s a few abstraction layers here.
- Top layer: The console class, which we can call WriteLine on.
- Managed stream wrapper: there are properties on the Console class: Console.In and Console.Out which represent the file streams in managed code
- Underlying window ‘standard input/output’ concepts: Windows tracks ‘standard input’ and ‘standard output’ file streams for a process, which seem like they are either wrapper objects, or logical indexes into a table of file handles.
- Raw file handle: suitable for passing to APIs that know and care about low level file handles, and don’t have concepts like standard input and standard output. APIs like ‘Read’ and ‘Write’ (bytes)
Calling SetStdHandle will let us insert our own file handle underneath the logical ‘standard input/standard output’ layer at the raw file handle layer. But we can only make each concept logically point at a single file handle, so what should we insert in order to have output in two places?
Read more: The Activity Designer
QR: