public static void EnsureConsoleOpen() { if (Environment.OSVersion.Platform.IsWindows()) { if (NativeWindowsConsole.StdOutFileHandle == IntPtr.Zero) { if (NativeWindows.AllocConsole() == false) { throw new InvalidOperationException(String.Format("Failed to create console (lasterror={0})", NativeWindows.GetLastError())); } NativeWindowsConsole.StdOutFileHandle = NativeWindows.GetStdHandle(NativeWindows.STD_OUTPUT_HANDLE); if (NativeWindowsConsole.StdOutFileHandle == NativeWindows.INVALID_HANDLE_VALUE) { throw new InvalidOperationException(String.Format("GetStdHandle(STD_OUTPUT_HANDLE) failed (error={0})", NativeWindows.GetLastError())); } if (NativeWindowsConsole.StdOutFileHandle == IntPtr.Zero) { throw new InvalidOperationException(String.Format("GetStdHandle(STD_OUTPUT_HANDLE) returned 0 but this doesn't make sense because we just called AllocConsole? (lasterror={0})", NativeWindows.GetLastError())); } NativeWindowsConsole.StdOutCodePage = NativeWindows.GetConsoleCP(); StdOut = BufferedWindowsConsoleSink.Create(64, true); } } else { throw new PlatformNotSupportedException(String.Format("No console implemented for platform: {0}", Environment.OSVersion.Platform)); } }
static NativeWindowsConsole() { StdOutFileHandle = NativeWindows.GetStdHandle(NativeWindows.STD_OUTPUT_HANDLE); if (StdOutFileHandle == NativeWindows.INVALID_HANDLE_VALUE) { throw new InvalidOperationException(String.Format("GetStdHandle(STD_OUTPUT_HANDLE) failed (error={0})", NativeWindows.GetLastError())); } if (StdOutFileHandle != IntPtr.Zero) { NativeWindowsConsole.StdOutCodePage = NativeWindows.GetConsoleCP(); } }
public static void Write(BytePtr buffer, UInt32 length) { UInt32 written = 0; if (!NativeWindows.TryWriteFile(StdOutFileHandle, buffer, length, out written, IntPtr.Zero)) { throw new InvalidOperationException(String.Format("WriteFile failed (lastError={0})", NativeWindows.GetLastError())); } if (written != length) { throw new InvalidOperationException(String.Format("Attempted to write {0} bytes but only wrote {1}", length, written)); } }