Waitforsingleobject

morulis

Member
Mar 5, 2005
89
0
0
#include "stdafx.h"

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
STARTUPINFO siStartupInfo;
PROCESS_INFORMATION piProcessInfo;

memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));

siStartupInfo.cb = sizeof(siStartupInfo);

if(CreateProcess("c:\\windows\\notepad.exe", // Application name
0, // Application arguments
0,
0,
FALSE,
CREATE_DEFAULT_ERROR_MODE,
0,
0, // Working directory
&siStartupInfo,
&piProcessInfo) == FALSE)
// Could not start application -> call 'GetLastError()'


// Wait until application has terminated
WaitForSingleObject(piProcessInfo.hProcess, INFINITE);
MessageBox(NULL, "Hello World", "Hello World", 0);
// Close process and thread handles
::CloseHandle(piProcessInfo.hThread);
::CloseHandle(piProcessInfo.hProcess);


return 0;
}

In the above code I try to make a program that will show a MessageBox when I close the "notepad" but this doesn't happen. The MsgBox and the "notepad" open together. What am I doing wrong?
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
In your code, the first statement that falls within the scope of your 'if' test is the WaitForSingleObject call. That means the WaitForSingleObject call will only get called if your 'if' statement evaluates to true (that is, the process failed to start). Since your process starts, the code continues with the next statement outside the 'if' block, which is the MessageBox call.

Add a ';' or an empty {} block after the if test, or actually implement the call to GetLastError mentioned in the comment.