c# 通过win32 api 得到指定Console application Content
已知的问题:
1. Windows 应用程序才可以使用,可以用非windows应用程序包一层
public class ConsoleContentRead { [DllImport("kernel32.dll", SetLastError = true)] static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FreeConsole(uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [StructLayout(LayoutKind.Sequential)] public struct Coord { public short X; public short Y; } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput, [Out] StringBuilder lpCharacter, uint length, Coord bufferCoord, out uint lpNumberOfCharactersRead); public static string ReadCharacterAt(int x, int y, int length) { IntPtr consoleHandle = GetStdHandle(-11); if (consoleHandle == IntPtr.Zero) { return null; } Coord position = new Coord { X = (short)x, Y = (short)y }; StringBuilder result = new StringBuilder(length); uint read = 0; if (ReadConsoleOutputCharacter(consoleHandle, result, (uint)length, position, out read)) { return result.ToString(); } else { return null; } } public static string GetContent(int pid, int x, int y, int length) { //注意要是 Windows 应用程序才可以 AttachConsole成功 var flag = AttachConsole((uint)pid); string content = ReadCharacterAt(x, y, length); var freeflag = FreeConsole((uint)pid); return content; } }
//使用 var content = ConsoleContentRead.GetContent(process.Id, 0, 2, 45);