1. 程式人生 > >在cmd啟動一個win32程序,printf把信息輸出到啟運它的那個CMD窗口

在cmd啟動一個win32程序,printf把信息輸出到啟運它的那個CMD窗口

mask lose orm fin current api query unique sep

#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窗口了。

在cmd啟動一個win32程序,printf把信息輸出到啟運它的那個CMD窗口