app_command/
app_command.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crossbeam_channel::unbounded;
use std::thread;
use win_hotkeys::HotkeyManager;
use win_hotkeys::VKey;

enum AppCommand {
    AppCommand1,
    AppCommand2,
    Exit,
}

fn main() {
    // The HotkeyManager is generic over the return type of the callback functions.
    let mut hkm = HotkeyManager::new();
    let modifiers = &[VKey::LWin, VKey::Shift];

    // Register WIN + SHIFT + 1 for app command 1
    hkm.register_hotkey(VKey::Vk1, modifiers, || {
        println!("Pressed WIN + SHIFT + 1");
        AppCommand::AppCommand1
    })
    .unwrap();

    // Register WIN + SHIFT + 2 for app command 2
    hkm.register_hotkey(VKey::Vk2, modifiers, || {
        println!("Pressed WIN + SHIFT + 2");
        AppCommand::AppCommand2
    })
    .unwrap();

    // Register WIN + 3 for app command EXIT
    hkm.register_hotkey(VKey::Vk3, modifiers, || {
        println!("Pressed WIN + SHIFT + 3");
        AppCommand::Exit
    })
    .unwrap();

    // Register channel to receive events from the hkm event loop
    let (tx, rx) = unbounded();
    hkm.register_channel(tx);

    // Run HotkeyManager in background thread
    let handle = hkm.interrupt_handle();
    thread::spawn(move || {
        hkm.event_loop();
    });

    // App Logic
    loop {
        let command = rx.recv().unwrap();

        match command {
            AppCommand::AppCommand1 => {
                println!("Do thing 1");
            }
            AppCommand::AppCommand2 => {
                println!("Do thing 2");
            }
            AppCommand::Exit => {
                println!("Exiting...");
                handle.interrupt();
                break;
            }
        }
    }
}