Last active
January 12, 2016 13:11
-
-
Save unarist/6944cdc44aaf22b1a654 to your computer and use it in GitHub Desktop.
別プロセスのコンソールバッファを読み取るサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for http://ja.stackoverflow.com/a/20861/ | |
using System; | |
using System.Diagnostics; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
using System.Threading; | |
using System.Windows.Forms; | |
namespace Sample | |
{ | |
class Program | |
{ | |
struct Coord | |
{ | |
public short X; | |
public short Y; | |
} | |
[DllImport("kernel32.dll", SetLastError = true)] | |
static extern bool AttachConsole(int dwProcessId); | |
[DllImport("kernel32.dll", SetLastError = true)] | |
static extern bool FreeConsole(); | |
[DllImport("kernel32.dll")] | |
static extern IntPtr GetStdHandle(int nStdHandle); | |
[DllImport("kernel32.dll", SetLastError = true)] | |
static extern bool ReadConsoleOutputCharacter( | |
IntPtr hConsoleOutput, | |
StringBuilder lpCharacter, | |
int nLength, | |
Coord dwReadCoord, | |
out int lpNumberOfCharsRead | |
); | |
static void Main(string[] args) | |
{ | |
var proc = Process.Start(new ProcessStartInfo("cmd.exe") { UseShellExecute = false }); | |
Thread.Sleep(1000); | |
// コンソールアプリの場合は最初のコンソールを切り離す必要がある | |
// FreeConsole(); | |
if (!AttachConsole(proc.Id)) | |
throw new InvalidOperationException("アタッチ失敗"); | |
var stdout = GetStdHandle(-11 /* STD_OUTPUT_HANDLE */); | |
// ここでは左上端から50文字固定だが、バッファ全体を読み出したいなら | |
// GetConsoleScreenBufferInfo() で縦横のサイズを調べて云々。 | |
// 行ごとに読み取るなりまとめて読み取るなり。 | |
var str = new StringBuilder(50); | |
int read; | |
if (!ReadConsoleOutputCharacter(stdout, str, str.Capacity, new Coord { X = 0, Y = 0 }, out read)) | |
throw new InvalidOperationException("読み取り失敗"); | |
MessageBox.Show(str.ToString(0, read)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment