HaPpY hApPy

콘솔 출력을 버프에 담기 winapi api win32 본문

.NET/WinApi

콘솔 출력을 버프에 담기 winapi api win32

juniguya 2013. 4. 15. 16:24
C#에서는 완전 쉬웠는데,,ㅡ,ㅡ
오늘 몇시간 삽질한건지 ㅋㅋ
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
SECURITY_ATTRIBUTES security_attributes;
HANDLE child_output_read;
HANDLE child_output_write;
TCHAR sz[20] = TEXT("ipconfig");
DWORD bytes_read;

CHAR bybuffer[4096];
wchar_t cbuffer[4096];

 security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
   security_attributes.bInheritHandle = TRUE;
   security_attributes.lpSecurityDescriptor = NULL;

   CreatePipe(&child_output_read, &child_output_write, &security_attributes, 0);

   startup_info.cb = sizeof(STARTUPINFO);
   startup_info.hStdOutput = child_output_write;
   startup_info.hStdError = child_output_write;
   startup_info.dwFlags |= STARTF_USESTDHANDLES;
   CreateProcess(NULL, sz, NULL, NULL, TRUE, 0, NULL, NULL, &startup_info, &process_info);
 ReadFile(child_output_read,bybuffer, sizeof(bybuffer), &bytes_read, NULL);  //byte 단위로 읽어옴
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, bybuffer, strlen(bybuffer),    //Wide 케릭으로 바꿔줘야함
                    cbuffer, 4096);


결과는 ipconfig 한 결과가 cbuffer에 들어간다.
readfile 하면 bybuffer에 들어가는데 Multibyte여서 다시 UNICODE로 바꿔주느라 MultiByteToWideChar를 사용했다.