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


#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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM