Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't winmain set the errorlevel?

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

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;
}

I compiled the code above to the name an executable called a.exe. The I did this in command prompt:

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

I get the same results if I use 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 saw this problem in a more complex program so I made this simple program to verify the problem. Results are the same, both programs that have WinMain always return 0.

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

like image 374
Brian R. Bondy Avatar asked Feb 26 '09 19:02

Brian R. Bondy


2 Answers

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%
like image 143
jdigital Avatar answered Sep 20 '22 14:09

jdigital


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"

like image 31
Michael Burr Avatar answered Sep 23 '22 14:09

Michael Burr