I can't get ExitCode to work for a VCL forms application. Here is my test application. It was created from the File / New menu in the Delphi 2007 IDE. The only change is that I added the line ExitCode := 42;
at the end.
program Test;
uses
Forms,
Unit27 in 'Unit27.pas' {Form27};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TForm27, Form27);
Application.Run;
ExitCode := 42;
end.
Now, when I run it from the command line, %ERRORLEVEL%
doesn't get set:
>.\Test.exe
>echo %ERRORLEVEL%
0
I was expected the value in %ERRORLEVEL%
to be 42, but it isn't being updated.
I tried the same experiment in a console application, and that worked fine. Why isn't it working for my GUI application?
Your method of setting the exit code is fine. It's your test that's faulty.
The shell doesn't wait for GUI applications to finish running before prompting for the next command. Thus, the error level has already been established. You're checking the value at the time the command prompt was displayed, not at the time you ran the echo
command.
Running programs in a batch file or command script modifies the behavior of the command interpreter to make it wait for each command to finish before running the next one, even for programs marked as using the GUI subsystem instead of the console subsystem. That's why the error level is reported correctly from batch files — the process you ran had finished before the command interpreter fetches the exit code. Without using a command script, you can try starting your program with the start
command and passing it the /wait
option. I'm not sure it forwards the exit code of the process it starts, though.