| 
 | 
 
 楼主 |
发表于 2005-6-4 10:55:28
|
显示全部楼层
 
 
 
如何定义个新的事件? As following: 
有两类方法: 
- 定义一个全新的事件类,典型的是从wxEvent或wxCommandEvent派生出来。 
- 使用现有的事件类(event class),但是给以新的类型(type)。 
在这两类方法中都必须声明这个新的事件类型: 
// in the header of the source file 
DECLARE_EVENT_TYPE(name, value) 
 
// in the implementation 
DEFINE_EVENT_TYPE(name) 
 
这里,value是没什么意义的,只是为了和wxWidgets 2.0.x保持兼容。 
 
◎ 使用现有的事件类 
如果你仅仅想使wxCommandEvent赋予一个新的类型,可以使用如下的方式 
(这样可以不必定义一个新的事件类,也不用实现使用于线程见通信时使用的wxEvent::Clone()) 
DECLARE_EVENT_TYPE(wxEVT_MY_EVENT, -1) 
 
DEFINE_EVENT_TYPE(wxEVT_MY_EVENT) 
 
// user code intercepting the event 
 
BEGIN_EVENT_TABLE(MyFrame, wxFrame) 
  EVT_MENU    (wxID_EXIT, MyFrame::OnExit) 
  // .... 
  EVT_COMMAND  (ID_MY_WINDOW, wxEVT_MY_EVENT, MyFrame::OnMyEvent) 
END_EVENT_TABLE() 
 
void MyFrame::OnMyEvent( wxCommandEvent &event ) 
{ 
    // do something 
    wxString text = event.GetText(); 
} 
 
 
// user code sending the event 
 
void MyWindow::SendEvent() 
{ 
    wxCommandEvent event( wxEVT_MY_EVENT, GetId() ); 
    event.SetEventObject( this ); 
    // Give it some contents 
    event.SetText( wxT("Hallo") ); 
    // Send it 
    GetEventHandler()->ProcessEvent( event ); 
} 
 
 
◎定义全新的事件类 
这某些情况下,你需要定义全新的事件类以实现复杂数据的传输。例子: 
 
// code defining event 
 
class wxPlotEvent: public wxNotifyEvent 
{ 
public: 
    wxPlotEvent( wxEventType commandType = wxEVT_NULL, int id = 0 ); 
 
    // accessors 
    wxPlotCurve *GetCurve() 
        { return m_curve; } 
 
    // required for sending with wxPostEvent() 
    wxEvent* Clone(); 
 
private: 
    wxPlotCurve   *m_curve; 
}; 
 
DECLARE_EVENT_MACRO( wxEVT_PLOT_ACTION, -1 ) 
 
typedef void (wxEvtHandler::*wxPlotEventFunction)(wxPlotEvent&); 
 
#define EVT_PLOT(id, fn) \ 
    DECLARE_EVENT_TABLE_ENTRY( wxEVT_PLOT_ACTION, id, -1, \ 
    (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) \ 
    wxStaticCastEvent( wxPlotEventFunction, & fn ), (wxObject *) NULL ), 
 
 
// code implementing the event type and the event class 
 
DEFINE_EVENT_TYPE( wxEVT_PLOT_ACTION ) 
 
wxPlotEvent::wxPlotEvent( ... 
 
// user code intercepting the event 
 
BEGIN_EVENT_TABLE(MyFrame, wxFrame) 
  EVT_PLOT  (ID_MY_WINDOW,  MyFrame::OnPlot) 
END_EVENT_TABLE() 
 
void MyFrame::OnPlot( wxPlotEvent &event ) 
{ 
    wxPlotCurve *curve = event.GetCurve(); 
} 
 
 
// user code sending the event 
 
void MyWindow::SendEvent() 
{ 
    wxPlotEvent event( wxEVT_PLOT_ACTION, GetId() ); 
    event.SetEventObject( this ); 
    event.SetCurve( m_curve ); 
    GetEventHandler()->ProcessEvent( event ); 
} 
 
◎几个宏的说明 |   
 
 
 
 |