// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; namespace E { public class ConsoleFun { [StructLayout(LayoutKind.Sequential)] struct COORD { public short x; public short y; } [StructLayout(LayoutKind.Sequential)] struct SMALL_RECT { public short Left; public short Top; public short Right; public short Bottom; } [StructLayout(LayoutKind.Sequential)] struct CONSOLE_SCREEN_BUFFER_INFO { public COORD dwSize; public COORD dwCursorPosition; public int wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; } private const uint STD_OUTPUT_HANDLE = 0xfffffff5; [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(uint h); [DllImport("kernel32.dll")] private static extern bool GetConsoleScreenBufferInfo(IntPtr h, out CONSOLE_SCREEN_BUFFER_INFO info); [DllImport("kernel32.dll")] static extern bool ReadConsoleOutputCharacter(IntPtr h, [Out] StringBuilder buf, uint buflen, COORD pos, out uint retlen); public static List GetContent() { IntPtr stdout = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(stdout, out info); List res = new List(); for(int i = 0; i < info.dwSize.y; i++) { COORD pos; pos.x = 0; pos.y = (short)i; StringBuilder line = new StringBuilder(); uint n; ReadConsoleOutputCharacter(stdout, line, (uint)info.dwSize.x, pos, out n); res.Add(line.ToString()); } return res; } } public class Program { public static void Main(string[] args) { StreamWriter sw = new StreamWriter("console.out"); foreach(string line in ConsoleFun.GetContent()) { sw.WriteLine(line); } sw.Close(); } } }