OVERVIEW
Every control or widget that you create is given an id. An id can be system-generated or it can be a predefined system id or you can give it an id of your choice. When you give a widget an id of -1 or wxID_ANY, then the system generates an id for that widget. System generated ids are negative eg. -1002, -2019 .
There are certain ids which are predefined like wxID_EXIT or wxID_NEW. The functions of these ids are preset in the system so they should not be used for something else than what they are meant to represent.
You can define your own ids as integer constants. By convention all user-defined ids should start from 101 onwards. You must ensure that all widgets have unique ids otherwise duplicate ids can cause runtime crashes.
The code below creates three buttons with ids generated in the three ways described above.
SAMPLE CODE
windows-ids.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
class WindowsIds: public wxFrame {
public:
WindowsIds(const wxString &title);
void OnClick(wxCommandEvent &event);
};
const int ID_BUTTON =101;
windows-ids-.cpp
#include "windows-ids.h"
WindowsIds::WindowsIds(const wxString &title):
wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,200)) {
wxPanel *panel = new wxPanel(this, -1);
wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL);
panel->SetSizer(hbox);
wxButton *btn1 = new wxButton(panel, -1, wxT("Auto Generated Id"));
wxButton *btn2 = new wxButton(panel, wxID_EXIT, wxT("System Id"));
wxButton *btn3 = new wxButton(panel, ID_BUTTON, wxT("User defined id"));
hbox->Add(btn1, 1, wxEXPAND | wxALL, 5);
hbox->Add(btn2, 1, wxEXPAND | wxALL, 5);
hbox->Add(btn3, 1, wxEXPAND | wxALL, 5);
btn1->Bind(wxEVT_BUTTON, &WindowsIds::OnClick, this);
btn2->Bind(wxEVT_BUTTON, &WindowsIds::OnClick, this);
btn3->Bind(wxEVT_BUTTON, &WindowsIds::OnClick, this);
Center();
}
void WindowsIds::OnClick(wxCommandEvent &event) {
wxString strId = wxString::Format(wxString("%d"), event.GetId());
wxMessageBox(strId);
}
main.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
class Main: public wxApp {
public:
virtual bool OnInit();
};
main.cpp
#include "main.h"
#include "windows-ids.h"
IMPLEMENT_APP(Main)
bool Main::OnInit() {
WindowsIds *app = new WindowsIds(wxT("Windows Ids"));
app->Show(true);
}
The output is shown below
Leave a Reply