Why does winmain not set the error level?

Why does this program correctly display a message box but do 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 above code for the name of an executable called a.exe. I did this on the command line:

 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. He still says 0 .

I also tried to run the program through CreateProcess and get the result using GetExitCodeProcess , but also returns 0 me. I checked error checking to make sure everything was running correctly.

I initially saw this problem in a more complex program, so I made this simple program to test the problem. The results are the same, both programs for which WinMain always returns 0 .

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

+6
c ++ visual-c ++ winapi winmain
source share
2 answers

If your program is a Windows application and not a console application, the command interpreter does not wait for completion (before clicking OK, take a look at the command window and you will see that it is ready for the next command).

If so, create the application as a console subsystem application to solve the problem. If you need to run a Windows application, you can try to wait for the command to finish and see if it works (I have not tried this, but it seems like a good approach):

 start /wait a.exe echo %ERRORLEVEL% 
+14
source share

For %ERRORLEVEL% to work, you need to enable command extensions (which, in my opinion, are standard, since God knows when).

Try to do:

 echo %CMDEXTVERSION% 

To find out if extensions are enabled. I get output " 2 " when they are turned on, and " %CMDEXTVERSION% " when they are turned off.

You can also check the error level using the old style:

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

This should work regardless of extensions or if someone set an environment variable named " ERRORLEVEL "

+2
source share

All Articles