why doesn't winmain set the errorlevel?

跟風遠走 提交于 2019-12-10 13:26:06

问题


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.


回答1:


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%



回答2:


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"



来源:https://stackoverflow.com/questions/592075/why-doesnt-winmain-set-the-errorlevel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!