views:

478

answers:

2
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
  MessageBox(NULL, _T("This should return 90 no?"), _T("OK"), MB_OK);
  return 90;
}

Why does the above program correctly display the message box, but does not set the error level?

I compile this program to the name a.exe. Then from command prompt I type:

c:\> a.exe 
 (message box is displayed, I press ok)
c:\> echo %ERRORLEVEL% 
  0

I get the same results if I do exit(90); right before the return. It still says 0.

I also tried to start the program via CreateProcess and obtain the result with GetExitCodeProcess but it also returns 0 to me. I did error checking to ensure it was all started correctly.

I originally seen this problem in a more complex program. But made this simple program to verify the problem. Results are the same, both programs that have WinMain return 0 always.

I tried both x64, x86 and unicode and MBCS compiling options. All give 0 as an error level/status code.

+5  A: 

If your program is a Windows app, rather than a Console app, the command interpreter doesn't wait for it to complete (before you press OK, take a look at the command window and you'll see that it's ready for the next command).

If this is the case, building your application as Console subsystem app would solve the problem. If you need to run as a Windows app, you might try to wait for the command to complete and see if that works (I haven't tried this but it seems like a good approach):

start /wait a.exe
echo %ERRORLEVEL%
jdigital
Thanks works. The problem I was having with CreateProcess returning 0 was a different one relating to the current working directory.
Brian R. Bondy
+1  A: 

For %ERRORLEVEL% to work you have to have command extensions enabled (which I think is the default since God know when).

Try doing:

echo %CMDEXTVERSION%

To see if extentions are enabled. I get '2' output when they are on and "%CMDEXTVERSION%" when they are off.

You can also test the errorlevel using the old style:

if errorlevel 1 echo errorlevel is 1 or more...

That should work regardless of extensions or if someone has set an enviroment variable with the name "ERRORLEVEL"

Michael Burr
Oh... I think that jdigital has hit the real problem on the head.
Michael Burr
yup thanks for the useful info though
Brian R. Bondy