Command-Line Arguments

From WxWiki
Jump to navigation Jump to search

Pitfalls

Given the below example, don't use parser.SetCmdLine(argc, argv);. This will set the parser to use a different command line parameters than what is passed to the program.

File Examples

#include <wx/wxprec.h>
#include <wx/cmdline.h>

#ifndef WX_PRECOMP
       #include <wx/wx.h>
#endif

class MyApp: public wxApp
{
public:

    // from wxApp
    virtual bool OnInit();
    virtual int OnExit();
    virtual int OnRun();
    virtual void OnInitCmdLine(wxCmdLineParser& parser);
    virtual bool OnCmdLineParsed(wxCmdLineParser& parser);

private:
    bool silent_mode;
};

static const wxCmdLineEntryDesc g_cmdLineDesc [] =
{
     { wxCMD_LINE_SWITCH, wxT("h"), wxT("help"), wxT("displays help on the command line parameters"),
          wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
     { wxCMD_LINE_SWITCH, wxT("t"), wxT("test"), wxT("test switch"),
          wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_MANDATORY  },
     { wxCMD_LINE_SWITCH, wxT("s"), wxT("silent"), wxT("disables the GUI") },

     { wxCMD_LINE_NONE }
};

DECLARE_APP(MyApp)
#include "main.h"

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
    // call default behaviour (mandatory)
    if (!wxApp::OnInit())
        return false;

    // some application-dependent treatments...

    // Show the frame
    wxFrame *frame = new wxFrame((wxFrame*) NULL, -1, _T("Hello wxWidgets World"));
    frame->CreateStatusBar();
    frame->SetStatusText(_T("Hello World"));
    frame->Show(TRUE);
    SetTopWindow(frame);
    return true;
}

int MyApp::OnExit()
{
    // clean up
    return 0;
}

int MyApp::OnRun()
{
    int exitcode = wxApp::OnRun();
    //wxTheClipboard->Flush();
    if (exitcode!=0)
        return exitcode;
}

void MyApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    parser.SetDesc (g_cmdLineDesc);
    // must refuse '/' as parameter starter or cannot use "/path" style paths
    parser.SetSwitchChars (wxT("-"));
}

bool MyApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    silent_mode = parser.Found(wxT("s"));

    // to get at your unnamed parameters use
    wxArrayString files;
    for (int i = 0; i < parser.GetParamCount(); i++)
    {
            files.Add(parser.GetParam(i));
    }

    // and other command line parameters

    // then do what you need with them.

    return true;
}

You may also need to look for wxApp::CleanUp() and wxApp::ProcessIdle().