Keyboard
Keyboard events are received through the trait OnKeyPressed defined as follows:
pub trait OnKeyPressed {
fn on_key_pressed(&mut self, key: Key, character: char) -> EventProcessStatus {
// do something depending on the key pressed
}
}
This method has two parameters:
- the
keyparameter (that provides information about the code of the key that was pressed and its modifiers) - the
character(when this is the case). This is usually when you want insert text intro a control (for example in case of a TextField)
Key
A key in AppCUI is defined as follows:
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Key {
pub code: KeyCode,
pub modifier: KeyModifier,
}
where:
codeis an enum that indicates a code for the key that was pressed and it includes:- F-commands (
F1toF12) - Letters (
AtoZ) - with apper case - Numbers (
0to9) - Arrows (
Up,Down,Left,Right) - Navigation keys (
PageUp,PageDown,Home,End) - Deletion and Insertions (
Delete,Backspace,Insert) - White-spaces (
Space,Tab) - Other (
Enter,Escape)
- F-commands (
modifiercan be one of the following (including combination between them):- Shift
- Ctrl
- Alt
The crete a key use:
Key::new(code, modifier)- for example:let k = Key::new(KeyCode::F1,KeyModifier::Alt | KeyModifier::Ctrl); let k2 = Key::new(KeyCode::Enter, KeyModifier::None);- using
Fromimplementation:let k = Key::from(KeyCode::F1); // this is equivalent to Key::new(KeyCode::F1, KeyModifier::None); key!macro - this can be used to create a key:let k1 = key!("F2"); let k2 = key!("Enter") let k3 = key!("Alt+F4") let k4 = key!("Ctrl+Alt+F") let k5 = key!("Ctrl+Shift+Alt+Tab")
Usage
The usual usage is via OnKeyPressed::on_key_pressed(...) method as follows:
impl OnKeyPressed for <MyControl> {
fn on_key_pressed(&mut self, key: Key, character: char) -> EventProcessStatus {
// check the key
match key.value() {
// check various key combinations
}
// check the character
match character {
// do something with the character
}
EventProcessStatus::Ignored
}
}
The following example checks the arrow keys for movement and ignores the rest of the keys:
impl OnKeyPressed for <MyControl> {
fn on_key_pressed(&mut self, key: Key, character: char) -> EventProcessStatus {
match key.value() {
key!("Left") => {
/* move left */
return EventProcessStatus::Processed;
}
key!("Right") => {
/* move right */
return EventProcessStatus::Processed;
}
key!("Ctrl+Left") => {
/* Move to begining */
return EventProcessStatus::Processed;
}
key!("Ctrl+Right") => {
/* Move to end */
return EventProcessStatus::Processed;
}
_ => {
return EventProcessStatus::Ignored;
}
}
}
}