vkeys_and_modkeys/
vkeys-and-modkeys.rs

1use windows_hotkeys::{
2    keys::{ModKey, VKey},
3    singlethreaded::HotkeyManager,
4    HotkeyManagerImpl,
5};
6
7fn main() {
8    // Create a HotkeyManager
9    let mut hkm = HotkeyManager::<()>::new();
10
11    // Create VKey from the enum variant (recommended if possible)
12    let vk_b1 = VKey::B;
13    let vk_up1 = VKey::Up;
14
15    // Create VKey from the case insensitive key char (only for 'a'-'z' and '0'-'9')
16    let vk_b2 = VKey::from_char('b').unwrap();
17    let vk_b3 = VKey::from_char('B').unwrap();
18
19    // Create VKey from key name string. This works with "A"-"Z", "0"-"9", the constant names
20    // "VK_*" and hex codes prefixed with "0x*"
21    // Useful when reading hotkeys in text form through config files or user input
22    let vk_b4 = VKey::from_keyname("b").unwrap();
23    let vk_b5 = VKey::from_keyname("B").unwrap();
24    let vk_b6 = VKey::from_keyname("0x42").unwrap();
25    let vk_up2 = VKey::from_keyname("VK_UP").unwrap();
26
27    // Create VKey directly from the virtual keycode
28    // See: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
29    let vk_b7 = VKey::CustomKeyCode(0x42);
30
31    // All of the methods are comparable with equal and usable for hashing
32    assert_eq!(vk_b1, vk_b2);
33    assert_eq!(vk_b1, vk_b3);
34    assert_eq!(vk_b1, vk_b4);
35    assert_eq!(vk_b1, vk_b5);
36    assert_eq!(vk_b1, vk_b6);
37    assert_eq!(vk_b1, vk_b7);
38
39    assert_eq!(vk_up1, vk_up2);
40
41    // **Alert**
42    // Matching the variants does not always work, since a key can be represented through the enum
43    // variant, or with a `CustomKeyCode`
44    match vk_b7 {
45        VKey::B => println!(
46            "CustomKeyCode(0x42) matches against B (this will not show up, because it is not true)"
47        ),
48        VKey::A => println!("Just checking if the key matches A"),
49        _ => println!("CustomKeyCode(0x42) does not match against B"),
50    }
51
52    // Instead use if chains if this is really needed for now, at least until a better solution is
53    // implemented
54    if vk_b7 == VKey::B {
55        println!("CustomKeyCode(0x42) is equal to B");
56    } else if vk_b7 == VKey::A {
57        println!("Just checking if the key is equal to A");
58    } else {
59        println!(
60            "CustomKeyCode(0x42) is not equal to B \
61            (this will not show up, because it works fine when using if)"
62        );
63    }
64
65    // Create ModKey from the enum variant
66    let mod_alt1 = ModKey::Alt;
67    // Create ModKey from key name string
68    let mod_alt2 = ModKey::from_keyname("ALT").unwrap();
69
70    // With modkeys, there is no `CustomKeyCode`, so they can be safely matched and compared
71    assert_eq!(mod_alt1, mod_alt2);
72
73    hkm.register_extrakeys(vk_b1, &[mod_alt1], &[vk_up1], || {
74        println!("Hotkey ALT + B + UP pressed");
75    })
76    .unwrap();
77
78    hkm.event_loop();
79}