Thursday, March 4, 2010

Synchronous execution of .exe file from VC++ application


Recently, in one of our project we have faced some difficulty in executing a windows/shell program from VC++ application.

Previously we used shellexecute () for calling a windows .exe file (e.g cmd.exe with some parameters) from VC++. But next step after calling shellexecute() started to begin its execution before the shell execution completes. It created some mess-ups.

We came to know that WaitForSingleObject can be used for synchronizing the execution.

But we have to use shellexecuteex () instead of shellexecute ().

And, syntax of shellexecuteex () will be different from shellexecute ().

You can refer the below sample code refered from codeguru.com

SHELLEXECUTEINFO lpExecInfo;

lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.lpFile = "c:\\one.exe"; //file name or whatever you want to open
lpExecInfo.fMask=SEE_MASK_DOENVSUBST|SEE_MASK_NOCLOSEPROCESS ;
lpExecInfo.hwnd = NULL;
lpExecInfo.lpVerb ="open"; // open, explore, or print
lpExecInfo.lpParameters = NULL;
lpExecInfo.lpDirectory = NULL;
lpExecInfo.nShow = SW_SHOW;
lpExecInfo.hInstApp = (HINSTANCE) SE_ERR_DDEFAIL ; //WINSHELLAPI BOOL WINAPI result;
ShellExecuteEx(&lpExecInfo); // explore, print, or open the exe file

//wait until a file is finished with working or the user closed it.
// another way of saying freez the program until one.exe is closed.
if(lpExecInfo.hProcess !=NULL)
{
::WaitForSingleObject(lpExecInfo.hProcess, INFINITE);
::CloseHandle(lpExecInfo.hProcess);
}


More Articles...


You can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog