bool CWinUtils::StartAndWaitForProgram( const char* szCommandLine, DWORD* pExitCode, int iShowWindowFlags )
{
STARTUPINFO sui;
PROCESS_INFORMATION pi;
memset( &sui, 0, sizeof( sui ) );
sui.cb = sizeof( sui );
sui.wShowWindow = iShowWindowFlags;
std::string strFileName = szCommandLine,
strCmdLine = szCommandLine;
if ( ( strFileName.length() )
&& ( strFileName[0] == '"' ) )
{
// der Pfad ist in Anführungszeichen gehalten
strCmdLine = strFileName;
strFileName = strFileName.substr( 1 );
if ( strFileName.find( '"' ) != std::string::npos )
{
strFileName = strFileName.substr( 0, strFileName.find( '"' ) );
}
}
else if ( strFileName.length() )
{
if ( strFileName.find( ' ' ) != std::string::npos )
{
strFileName = strFileName.substr( 0, strFileName.find( ' ' ) );
}
}
std::string strCurDir = strFileName.c_str();
while ( ( strCurDir.length() )
&& ( strCurDir[strCurDir.length() - 1] != '\\' ) )
{
strCurDir = strCurDir.substr( 0, strCurDir.length() - 1 );
}
if ( strCurDir.length() )
{
strCurDir = strCurDir.substr( 0, strCurDir.length() - 1 );
}
if ( strCurDir.length() == 2 )
{
strCurDir += '\"';
}
char szCmdLine[MAX_PATH];
wsprintf( szCmdLine, strCmdLine.c_str() );
if ( !CreateProcess( strFileName.c_str(),
szCmdLine,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
NULL,
strCurDir.c_str(),
&sui,
&pi ) )
{
return false;
}
MSG msg;
DWORD dwExitCode = STILL_ACTIVE;
do
{
Sleep( 20 );
if ( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) )
{
GetMessage( &msg, NULL, 0, 0 );
if ( IsDialogMessage( ::GetParent( msg.hwnd ), &msg ) )
{
continue;
}
if ( msg.message == WM_ENDSESSION )
{
if ( (BOOL)msg.wParam )
{
// das aufgerufene Programm will Windows beenden
// -> Loop beenden
break;
}
}
TranslateMessage( &msg );
DispatchMessage( &msg );
}
GetExitCodeProcess( pi.hProcess, &dwExitCode );
}
while ( dwExitCode == STILL_ACTIVE );
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
if ( pExitCode != NULL )
{
*pExitCode = dwExitCode;
}
return true;
}