OVERVIEW
In this section, we will add a submenu to the File menu from the previous section and we will put the event handler on the menubar object so that all the menu items will be handled within a single click handler.
SAMPLE CODE
menus.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/menu.h>
class Menus: public wxFrame {
public:
Menus(const wxString& title);
void OnMenuItem(wxCommandEvent &evt);
wxMenuBar *mb;
wxMenu *mnuFile;
wxMenu *mnuEdit;
wxMenu *submenu;
};
const int ID_NEW = 101;
const int ID_SAVE = 102;
const int ID_OPEN = 103;
const int ID_SUB_ONE = 201;
const int ID_SUB_TWO = 202;
const int ID_SUB_THREE = 203;
menus.cpp
#include "menus.h"
Menus::Menus(const wxString& title):
wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,300)) {
mb = new wxMenuBar();
mnuFile = new wxMenu();
wxMenuItem *mniFileNew = new wxMenuItem(mnuFile, ID_NEW, wxT("&New.."));
mnuFile->Append(mniFileNew);
mnuFile->Append(ID_SAVE, wxT("&Save.."));
mnuFile->Append(ID_OPEN, wxT("&Open.."));
mnuFile->AppendSeparator();
submenu = new wxMenu();
submenu->Append(ID_SUB_ONE, wxT("Menu item one"));
submenu->Append(ID_SUB_TWO, wxT("Menu item two"));
submenu->Append(ID_SUB_THREE, wxT("Menu item three"));
mnuFile->AppendSubMenu(submenu, wxT("&Submenu"));
mnuFile->AppendSeparator();
mnuFile->Append(wxID_EXIT, wxT("&Quit"));
mb->Bind(wxEVT_MENU, &Menus::OnMenuItem, this);
mnuEdit = new wxMenu();
mnuEdit->Append(-1, wxT("Copy\tCtrl-C"));
mnuEdit->Append(-1, wxT("Paste\tCtrl-V"));
mnuEdit->Append(-1, wxT("Cut\tCtrl-X"));
mb->Append(mnuFile, wxT("&File"));
mb->Append(mnuEdit, wxT("&Edit"));
SetMenuBar(mb);
}
void Menus::OnMenuItem(wxCommandEvent &evt) {
int eventId= evt.GetId();
wxString strId = wxT("");
strId = wxString::Format(wxT("%d"), evt.GetId());
wxPuts(strId);
if (eventId == ID_NEW)
wxLogMessage("New file menuitem");
else if (eventId == ID_SAVE )
wxLogMessage("Save file menuitem");
else if (eventId == ID_OPEN)
wxLogMessage("Open file menuitem");
else if (eventId == wxID_EXIT)
Close(true);
}
The output is given below
Leave a Reply