Skip to main content

record_hotkey/
record_hotkey.rs

1//! Example: Record a hotkey from keyboard input
2//!
3//! This example demonstrates how to use KeyboardListener to capture
4//! keyboard events for a "record hotkey" UI flow.
5//!
6//! Run with: cargo run --example record_hotkey
7
8use handy_keys::{KeyboardListener, Result};
9use std::time::Duration;
10
11fn main() -> Result<()> {
12    println!("Recording keyboard events...");
13    println!("Press keys to see events. Press Escape to exit.");
14    println!();
15
16    let listener = KeyboardListener::new()?;
17
18    loop {
19        // Non-blocking check for events
20        if let Some(event) = listener.try_recv() {
21            let state = if event.is_key_down { "DOWN" } else { "UP" };
22
23            // Build a display string for the current combination
24            let combo = if event.modifiers.is_empty() {
25                match event.key {
26                    Some(key) => format!("{}", key),
27                    None => "(no key)".to_string(),
28                }
29            } else {
30                match event.key {
31                    Some(key) => format!("{}+{}", event.modifiers, key),
32                    None => format!("{}", event.modifiers),
33                }
34            };
35
36            println!("[{}] {}", state, combo);
37
38            // Check for Escape to exit
39            if event.key == Some(handy_keys::Key::Escape) && event.is_key_down {
40                println!("\nEscape pressed, exiting...");
41                break;
42            }
43        }
44
45        // Small sleep to avoid busy-waiting
46        std::thread::sleep(Duration::from_millis(10));
47    }
48
49    Ok(())
50}