1. 程式人生 > >VC常用程式碼之建立程序

VC常用程式碼之建立程序

作者:朱金燦

           建立程序是程式設計開發的常用操作。Windows中的建立程序採用API函式CreateProcess實現。下面是一個使用例子:

#include <Windows.h>
#include <string>

int _tmain(int argc, _TCHAR* argv[])
{

	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pi, sizeof(pi) );

	std::string strCmdLine = "ping www.baidu.com";
 
	// Start the child process. 
	if( !CreateProcess( NULL,   // No module name (use command line)
		(LPSTR)strCmdLine.c_str(),        // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory 
		&si,            // Pointer to STARTUPINFO structure
		&pi)           // Pointer to PROCESS_INFORMATION structure
		) 
	{
		printf( "CreateProcess failed (%d)\n", GetLastError() );
		return 1;
	}

	// Wait until child process exits.
	WaitForSingleObject( pi.hProcess, INFINITE );

	// Close process and thread handles. 
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );

   getchar();
   return 0;
}

        使用上面的方式建立程序會出現一個控制檯介面。要隱藏這個控制檯介面,只需要將CreateProcess函式的第六個引數設為CREATE_NO_WINDOW,比如上面對應的程式碼應改為:

	if( !CreateProcess( NULL,   // No module name (use command line)
		(LPSTR)strCmdLine.c_str(),        // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		CREATE_NO_WINDOW,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory 
		&si,            // Pointer to STARTUPINFO structure
		&pi)           // Pointer to PROCESS_INFORMATION structure
		) 
	{
		printf( "CreateProcess failed (%d)\n", GetLastError() );
		return 1;
	}