keyboard_input_usage/
keyboard_input_usage.rs

1//! 运行: cargo run --example keyboard_input_usage
2
3use keyboard_codes::{current_platform, KeyParseError, KeyboardInput};
4
5fn main() -> Result<(), KeyParseError> {
6    // 1. 从字符串创建 KeyboardInput
7    let key_a = "A".parse::<KeyboardInput>()?;
8    let modifier_ctrl = "Control".parse::<KeyboardInput>()?;
9    let _alias_esc = "esc".parse::<KeyboardInput>()?; // 使用别名
10
11    // 2. 类型检查与转换
12    println!("key_a 是普通键: {}", key_a.is_key()); // true
13    println!("modifier_ctrl 是修饰键: {}", modifier_ctrl.is_modifier()); // true
14
15    if let Some(key) = key_a.as_key() {
16        println!("获取内部 Key: {}", key);
17    }
18
19    // 3. 平台键码转换
20    let platform = current_platform();
21    let code_a = key_a.to_code(platform);
22    println!("A 键在 {} 的键码: 0x{:02X}", platform, code_a);
23
24    // 4. 从键码反解析
25    if let Some(parsed) = KeyboardInput::from_code(code_a, platform) {
26        println!("从键码反解析: {}", parsed);
27    }
28
29    // 5. 高级解析(带别名和大小写不敏感)
30    let inputs = ["Ctrl", "SHIFT", "alt", "F1", "space"];
31    println!("\n高级解析测试:");
32    for input in inputs {
33        match KeyboardInput::parse_with_aliases(input) {
34            Ok(kb_input) => println!("  '{}' -> {}", input, kb_input),
35            Err(e) => println!("  '{}' 解析失败: {}", input, e),
36        }
37    }
38
39    // 6. 显示实现
40    println!("\nDisplay 实现:");
41    println!("{} + {} = 组合键", modifier_ctrl, key_a);
42
43    Ok(())
44}