Search code examples
c++command-lineinitializationwxwidgetsexit-code

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();
}

Solution

  • 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;
    }