Native Windows Derive: Events
After defining the controls, it's time to bind the events. Every events defined in a Ui struct will be regrouped in
a single event hook.
Events base
Events are bound to control using the
nwg_events
attribute. It takes a list of event type and event callbacks.
Template:
nwg_events( EVENT_TYPE: [CALLBACK(ARGS),*] )
Details:
- EVENT_TYPE is any value of the
Event
enum.
- CALLBACK is the function that will be called when the event is triggered.
- ARGS specifies the parameters of the callback (optional, see the next section).
Example:
#[nwg_events(
OnButtonClick: [TestApp::callback1, TestApp::callback2],
OnMouseMove: [TestApp::callback3(SELF, CTRL)]
)]
window: nwg::Button,
Events arguments
By default, native windows derive assumes the callback is a method of the Ui structure. So for example,
TestApp::callback1
assumes the method has the following signature
callback1(&self)
.
That's very limiting. For example, if the same callback is used by two different controls, there's no way to differenciate them.
In order to fix this, NWD lets you define the callbacks parameters using those identifiers:
- SELF: Sends the ui struct
&UiStruct
. If there are no parameters, this is the default.
- RC_SELF: Sends the rc ui struct
&Rc<UiStruct>
. Useful for binding dynamic events
- CTRL: Sends the control that triggered the event. Ex:
&Button
- HANDLE: Sends the handle of the control.
&ControlHandle
- EVT: Sends the event that was triggered.
&Event
- EVT_DATA: Sends the data of the event that was triggered.
&EventData
It's also possible to not use any parameters, ex:
TestApp::callback1()
.
Example
pub struct Demo {
//...
#[nwg_events(
OnButtonClick: [Demo::button1, Demo::button2], // Multiple callbacks
OnMouseMove: [Demo::moving(SELF, CTRL), Demo::move2()], // With custom params & for a static method
)]
add_message_btn: nwg::Button,
}
Some events are defined as sub enums (ex:
MousePress
). In those case, the sub enums values must be used. For example,
if someone wants to handle a "left up events", a code similar to this should be used:
pub struct Demo {
#[nwg_control]
#[nwg_events(MousePressLeftUp: [Demo::test],)]
frame1: nwg::Frame,
}