Adding A Menubar

From WxWiki
Jump to navigation Jump to search

Menus make up an important role in any application. They serve as a single location where most users know they can find access to any feature or mode in your application. wxWidgets provides three main classes for managing menus in your application: wxMenuBar, wxMenu, and wxMenuItem.

Each menu item needs a unique ID. #define isn't used for defining constants (e.g. #define MENU_FILE_MENU 1) because this can't guarantee unique ID's. It's quite easy to overlook some values and it's difficult to maintain when you have to insert new ID's. If not defining menu IDs using enumerations, the second most popular way of defining IDs is to use the wxNewId() function for returning an unused ID.

Please have also a look into the wxWidgets manual, because the wxWidgets distribution has some very useful predefined IDs which you may want to (or even be required to) use, especially if you want to use a doc/view framework.

#ifndef _TEXTFRAME_H
#define _TEXTFRAME_H

class TextFrame : public wxFrame

    /** Constructor. Creates a new TextFrame */
    TextFrame(const wxChar *title, int xpos, int ypos, int width, int height);


    wxTextCtrl *m_pTextCtrl;
    wxMenuBar *m_pMenuBar;
    wxMenu *m_pFileMenu;
    wxMenu *m_pHelpMenu;

The menubar is created in the constructor of TextFrame as seen below. A menu-item is added to the menu using the Append method of wxMenu. Note how the ampersand is used to indicate which character is used as the mnemonic (not the keyboard shortcut). When the menu is created you use Append of wxMenuBar to append it to the menubar.

// For compilers that supports precompilation , includes "wx/wx.h"
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
    #include "wx/wx.h"
#include "TextFrame.h"

TextFrame::TextFrame(const wxChar *title, int xpos, int ypos, int width, int height)
    : wxFrame((wxFrame *) NULL, -1, title, wxPoint(xpos, ypos), wxSize(width, height))
    m_pTextCtrl = new wxTextCtrl(this, -1, _T("Type some text..."),
                       wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE);

    m_pMenuBar = new wxMenuBar();
    // File Menu
    m_pFileMenu = new wxMenu();
    m_pFileMenu->Append(wxID_OPEN, _T("&Open"));
    m_pFileMenu->Append(wxID_SAVE, _T("&Save"));
    m_pFileMenu->Append(wxID_EXIT, _T("&Quit"));
    m_pMenuBar->Append(m_pFileMenu, _T("&File"));
    // About menu
    m_pHelpMenu = new wxMenu();
    m_pHelpMenu->Append(wxID_ABOUT, _T("&About"));
    m_pMenuBar->Append(m_pHelpMenu, _T("&Help"));


next: Adding A Statusbar