Introduction
In one of my programs, I needed to wait until an external application finished processing some data, and wanted to minimize the main window during that time to prevent the user from doing anything else before the results were available. That's why I wrote CreateProcessEx
.
The CreateProcessEx
function takes seven parameters but only the first two are required:
DWORD CreateProcessEx ( LPCSTR lpAppPath, LPCSTR lpCmdLine,
BOOL bAppInCmdLine, BOOL bCompletePath,
BOOL bWaitForProcess, BOOL bMinimizeOnWait, HWND hMainWnd ) {
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
char szAppPath [ _MAX_PATH ];
char szCmdLine [ _MAX_PATH ];
char drive [ _MAX_DRIVE ];
char dir [ _MAX_DIR ];
char name [ _MAX_FNAME ];
char ext [ _MAX_EXT ];
szAppPath[ 0 ] = '\0';
szCmdLine[ 0 ] = '\0';
ZeroMemory( &startupInfo, sizeof( STARTUPINFO ));
startupInfo.cb = sizeof( STARTUPINFO );
ZeroMemory( &processInformation, sizeof( PROCESS_INFORMATION ));
if ( bCompletePath ) {
GetModuleFileName( GetModuleHandle( NULL ), szAppPath, _MAX_PATH );
_splitpath( szAppPath, drive, dir, NULL, NULL );
_splitpath( lpAppPath, NULL, NULL, name, ext );
_makepath ( szAppPath, drive, dir, name, strlen( ext ) ? ext : ".exe" );
}
else strcpy( szAppPath, lpAppPath );
if ( bAppInCmdLine ) {
strcpy( szCmdLine, "\"" );
strcat( szCmdLine, szAppPath );
strcat( szCmdLine, "\"" );
}
if ( lpCmdLine ) {
if ( bAppInCmdLine ) strcat( szCmdLine, " \"" );
else strcpy( szCmdLine, "\"" );
strcat( szCmdLine, lpCmdLine );
strcat( szCmdLine, "\"" );
}
DWORD dwExitCode = -1;
if ( CreateProcess( bAppInCmdLine ? NULL: szAppPath,
szCmdLine,
0,
0,
FALSE,
DETACHED_PROCESS,
0,
0,
&startupInfo,
&processInformation
)) {
if ( bWaitForProcess ) {
if ( bMinimizeOnWait )
if ( IsWindow( hMainWnd )) ShowWindow( hMainWnd, SW_MINIMIZE );
#ifdef __AFX_H__
else AfxGetMainWnd()->ShowWindow( SW_MINIMIZE );
#endif
WaitForSingleObject( processInformation.hProcess, INFINITE );
if ( bMinimizeOnWait )
if ( IsWindow( hMainWnd )) ShowWindow( hMainWnd, SW_RESTORE );
#ifdef __AFX_H__
else AfxGetMainWnd()->ShowWindow( SW_RESTORE );
#endif
GetExitCodeProcess( processInformation.hProcess, &dwExitCode );
}
else {
CloseHandle( processInformation.hThread );
CloseHandle( processInformation.hProcess );
dwExitCode = 0;
}
}
return dwExitCode;
}
To use the function, simply include the CreateProcessEx.h and CreateProcessEx.cpp files in your project. That's it!