mromeo
asked on
How do you return an exit code from an MFC application?
I have an MFC application which is a Windows service. If this application is run on the command line with a certain flag (-r), instead of starting the service, it merely tests to see if this service is running and then returns 1 or 0, depending on the result. For example:
MyService -r
returns 0 if MyService is not running and 1 if it is running
Now, I want to be able to write a bat file to capture the exit code and say something like:
MyService -r
if %errorlevel% 1 then goto running
if %errorlevel% 0 then goto notrunning
etc....
The problem is, the MFC app always returns 0, regardless if it is running or not. I have overridden ExitInstance to return the value and when I log that value, it is correect. But when the app gets back to the Windows shell, the errorlevel value is always 0. Here is my ExitInstance code. Is there something else that I need to override to get the correct exit code to back to the DOS shell? Thanks!
BOOL CMainApp::ExitInstance()
{
if (__argc > 1 && (strcmp(__argv[1], "-r") == 0 ))
{
// check to see if the service is running
BOOL running = IsServiceRunning(GetServic eName()); // calls QueryServiceStatus, etc.
return (running);
}
else
{
return (CWinApp::ExitInstance());
}
}
MyService -r
returns 0 if MyService is not running and 1 if it is running
Now, I want to be able to write a bat file to capture the exit code and say something like:
MyService -r
if %errorlevel% 1 then goto running
if %errorlevel% 0 then goto notrunning
etc....
The problem is, the MFC app always returns 0, regardless if it is running or not. I have overridden ExitInstance to return the value and when I log that value, it is correect. But when the app gets back to the Windows shell, the errorlevel value is always 0. Here is my ExitInstance code. Is there something else that I need to override to get the correct exit code to back to the DOS shell? Thanks!
BOOL CMainApp::ExitInstance()
{
if (__argc > 1 && (strcmp(__argv[1], "-r") == 0 ))
{
// check to see if the service is running
BOOL running = IsServiceRunning(GetServic
return (running);
}
else
{
return (CWinApp::ExitInstance());
}
}
ASKER
I am doing that. But yet, when I type "echo %errorlevel%" at a command prompt right after my program exits, it always returns 0....regardless of the vaule returned by ExitInstance. I know my return value from ExitInstance is correct because I was logging it, and it definitely was NOT zero. Any ideas?? Could this be an ms-dos issue?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Ok, so my code is correct. I will try this in a bat file. Tahnks.
If you want to call CWinApp::ExitInstance and return your own value, you can write:
CWinApp::ExitInstance();
return myExitCode;