OVERVIEW
We are going to create an application with a menubar containing menus. Each menu will contain some menu items and we will add an event handler to handle clicks on the menu items. We have added an event handler only to the File menu and not the Edit Menu in this case.
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;
};
const int ID_NEW = 101;
const int ID_SAVE = 102;
const int ID_OPEN = 103;
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();
mnuFile->Append(wxID_EXIT, wxT("&Quit"));
mnuFile->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 shown below:
Leave a Reply