Wednesday, April 1, 2009

Synchronous process execution from VC++


Following is the Sample code for executing a process in VC++ synchronously. We can use System command also but that display a command propmt flash also. To avoid command prompt flash i have used earlier ShellExecute API but that runs a process Asynchronously.

ShellExecute(NULL,NULL,"C:\\Test.exe","Test Argument Param",NULL,SW_HIDE);

ShellExecute just returns the value 42 [If it fails return value is suppose to be <= 32] and program execution proceed to next line of code. This can create problem when one want ShellExecute to complete it's processing before it go to next line of code in program. Following is the solution i implemented for the same after avoiding ShellExecute and ShellExecuteEx APIs.

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

si.dwFlags = STARTF_USESHOWWINDOW; // For enabling custon flags e.g. wShowWindow
si.wShowWindow = SW_HIDE; // For hiding the window of application
ZeroMemory( &pi, sizeof(pi) );
if (!CreateProcess( "C:\\Test.exe"," Test Argument Param",NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
{ printf("%s\n","ProcessFailed"); }
WaitForSingleObject( pi.hProcess, INFINITE ); // Wait until child process exits.
CloseHandle( pi.hProcess ); // Close process and thread handles.
CloseHandle( pi.hThread );

Please do comment if need anything furthur.

No comments:

Post a Comment