#define ProcessBasicInformation 0
typedef struct
{
DWORD ExitStatus;
DWORD PebBaseAddress;
DWORD AffinityMask;
DWORD BasePriority;
ULONG UniqueProcessId;
ULONG InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;
typedef LONG (WINAPI *PROCNTQSIP)(HANDLE, UINT, PVOID, ULONG, PULONG);
PROCNTQSIP NtQueryInformationProcess;
在CWinApp::InitInstance()中添加:
NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(GetModuleHandle(L"ntdll.dll"),
"NtQueryInformationProcess");
HANDLE hProcess;
PROCESS_BASIC_INFORMATION pbi;
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,GetCurrentProcessId());
NtQueryInformationProcess(hProcess, ProcessBasicInformation, (PVOID)&pbi,
sizeof(PROCESS_BASIC_INFORMATION), NULL);
CloseHandle(hProcess);
AttachConsole(pbi.InheritedFromUniqueProcessId);
freopen("CONOUT$","w",stdout); // 重定向输出
用printf函数就可以把信息输出到启运它的那个CMD窗口了。
方法二:
AttachConsole(ATTACH_PARENT_PROCESS); // 将当前程序附着到父进程上,因为是从控制台启动的,所以当前程序的父进程就是那个控制台。
freopen("CONIN$", "r+t", stdin); // 重定向 STDIN
freopen("CONOUT$", "w+t", stdout); // 重定向STDOUT