crossterm/examples/event-match-modifiers.rs
Josh McKinney e063091312
Add is_* and as_* methods to the event enums (#949)
* Add is_ and as_ methods to the event enums

Often application code only cares about a small subset of possible
events. These methods make it simpler to write code which checks whether
an event is a particular event type or converts events into the specific
type (returning an Option).

This can help simplify some nested match blocks. E.g.:

```rust
match event {
    Event::Key(key) if key.kind == KeyEventKind::Press => { ... }
}
```

becomes:

```rust
if let Some(key) = event.as_key_press() { ... }
```

Similar flexible methods are aded across all the event enums:

- `Event::is_focus_gained()`
- `Event::is_focus_lost()`
- `Event::is_key()`
- `Event::is_mouse()`
- `Event::is_paste()`
- `Event::is_resize()`
- `Event::is_key_press()`
- `Event::as_key_press() -> Option<&KeyEvent>`
- `MouseEventKind::is_*()`
- `MouseButton::is_*()`
- `KeyEventKind::is_*()`
- `KeyEvent::is_press()`
- `KeyEvent::is_release()`
- `KeyEvent::is_repeat()`
- `KeyCode::is_*()`
- `KeyCode::is_function_key(n)`
- `KeyCode::is_char(c)`
- `KeyCode::as_char() -> Option<char>`
- `KeyCode::is_media_key(media)`
- `KeyCode::is_modifier(modifier)`
- add is_key_release() and is_key_repeat() checks
- add as_key_event()
- rename as_key_press() to as_key_press_event()
- add as_key_repeat_event()
- add as_key_release_event()
- add as_mouse_event()
- add as_paste_event()
- more tests
- update event-match and key-display examples
2025-02-02 11:31:10 +01:00

68 lines
1.8 KiB
Rust

//! Demonstrates how to match on modifiers like: Control, alt, shift.
//!
//! cargo run --example event-match-modifiers
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
fn match_event(event: Event) {
if let Some(key) = event.as_key_press_event() {
match key {
KeyEvent {
modifiers: KeyModifiers::CONTROL,
code,
..
} => {
println!("Control + {:?}", code);
}
KeyEvent {
modifiers: KeyModifiers::SHIFT,
code,
..
} => {
println!("Shift + {:?}", code);
}
KeyEvent {
modifiers: KeyModifiers::ALT,
code,
..
} => {
println!("Alt + {:?}", code);
}
// Match on multiple modifiers:
KeyEvent {
code, modifiers, ..
} => {
if modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT) {
println!("Alt + Shift {:?}", code);
} else {
println!("({:?}) with key: {:?}", modifiers, code)
}
}
}
}
}
fn main() {
match_event(Event::Key(KeyEvent::new(
KeyCode::Char('z'),
KeyModifiers::CONTROL,
)));
match_event(Event::Key(KeyEvent::new(
KeyCode::Left,
KeyModifiers::SHIFT,
)));
match_event(Event::Key(KeyEvent::new(
KeyCode::Delete,
KeyModifiers::ALT,
)));
match_event(Event::Key(KeyEvent::new(
KeyCode::Right,
KeyModifiers::ALT | KeyModifiers::SHIFT,
)));
match_event(Event::Key(KeyEvent::new(
KeyCode::Home,
KeyModifiers::ALT | KeyModifiers::CONTROL,
)));
}