当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to properly close application with exit code

问题描述:

In my wxWidgets application I am checking for a command line arguement, and if I find it, I do an action then I close the window. However, I can't seem to get the application to close properly. I want to close the program with an exit code, such as 3. When I check for the command line parameter in wxApp::OnInit, I tried to just call exit(3), however, this seemed to be improper as it caused memory leaks somewhere within wxwidgets.

I then tried to store the exit code, override OnRun and return there, however, when I do I get a crash in init.cpp line 472 on return wxTheApp->OnRun();.

Does anyone know how I can properly close the application with a custom exit code from wxApp after detecting the application should close? I also tried to overload wxApp::OnExit, however, it never ends up being called, even when I don't overload OnRun.

Code example at http://codepad.org/WYiOJq55 due to the code not being allowed in this post for some reason

EDIT Paste of the code:

int SomeApplication::OnRun()

{

if(mExitCode != 0)

{

ExitMainLoop();

return mExitCode;

}

else

return wxApp::OnRun();

}

网友答案:

Based upon your comments it seems that you do not ever launch a wxFrame and want to just exit an application as soon as possible. To do this, have your constructor for SomeApplication initialize mExitCode to 0. Then during OnInit do your command line argument check, and if you want to close your application immediantly after the check, set mExitCode to your exit code and return true from OnInit.

The following is how your OnRun function would work without ever opening another window.

int SomeApplication::OnRun()
{
    if(mExitCode == 0)
        wxApp::OnRun();

    return mExitCode;
}
网友答案:

When I override wxAPP::OnRun() like this:

int MyApp::OnRun()
{
    wxApp::OnRun();
    return 3;
}

Everything works just fine

If I create a little batch file

minimal.exe
echo el is %ERRORLEVEL%

it produces the expected result

>test.bat

>minimal.exe

>echo el is 3
el is 3

I think the problem with your code

int SomeApplication::OnRun()
{
    if(mExitCode != 0)
    {
        ExitMainLoop();
        return mExitCode;
    }
    else
        return wxApp::OnRun();
}

is that you are not calling the base class OnRun BEFORE checking your exit code, presumably set somewhere in the code executed by wxAPP::OnRun()

So I am guessing this will work for you

int SomeApplication::OnRun()
{
    wxApp::OnRun();
    return mExitCode;
 }
分享给朋友:
您可能感兴趣的文章:
随机阅读: