Rust實現hotkey

Jacek_Yang發表於2024-04-19

最近想寫一個快捷啟動工具來滿足自己的需求,剛好用自己最喜歡的 Rust 來實現

實現方法

文件: global_hotkey

具體程式碼

use global_hotkey::{
    hotkey::{Code, HotKey, Modifiers},
    GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState,
};
use winit::event_loop::{ControlFlow, EventLoopBuilder};

fn main() {
    let event_loop = EventLoopBuilder::new().build().unwrap();

    let hotkeys_manager = GlobalHotKeyManager::new().unwrap();

    let hotkey = HotKey::new(Some(Modifiers::SHIFT | Modifiers::ALT), Code::KeyD);

    hotkeys_manager.register(hotkey).unwrap();

    let global_hotkey_channel = GlobalHotKeyEvent::receiver();

    event_loop
        .run(move |_event, event_loop| {
            event_loop.set_control_flow(ControlFlow::Poll);

            if let Ok(event) = global_hotkey_channel.try_recv() {
                if hotkey.id() == event.id && event.state == HotKeyState::Released {
                    println!("快捷鍵啟動!!");
                }
            }
        })
        .unwrap();
}

實現效果

相關文章