在 tauri_hotkey 中删除点击监听器

Remove listener on click in tauri_hotkey

添加键盘键侦听器,当按下该键时我想删除该侦听器,我使用此 crates

添加监听器工作正常

use tauri_hotkey;

fn main() {
    let mut hotkey = tauri_hotkey::HotkeyManager::new();
    let key = tauri_hotkey::Hotkey {
        keys: vec![tauri_hotkey::Key::A],
        modifiers: vec![],
    };
    hotkey
        .register(key, || {
            println!("You pressed A",);
        })
        .unwrap();

    loop {} // infinate loop for prevent main from existing
}

移除点击按键时的监听器

    hotkey
        .register(key, || { 
            hotkey.unregister(&key).unwrap();
        })
        .unwrap();

它给出了一个编译错误说

cannot borrow `hotkey` as mutable more than once at a time
    
second mutable borrow occurs hererustc(E0499)
main.rs(29, 5): second mutable borrow occurs here
main.rs(30, 24): first mutable borrow occurs here
main.rs(32, 14): first borrow occurs due to use of `hotkey`

有什么方法可以解决这个问题,访问闭包内的热键吗?

注册签名甚至不允许您更改“热键”。首先是“&mut self”约束,其次是应该是 'static

的回调
  pub fn register<F>(&mut self, hotkey: Hotkey, callback: F) -> Result<()>
  where
    F: 'static + FnMut() + Send

一种方法可能是这样的

use std::sync::{Arc, Mutex};
use tauri_hotkey;

fn main() {
    let mut hotkey = tauri_hotkey::HotkeyManager::new();

    let key = tauri_hotkey::Hotkey {
        keys: vec![tauri_hotkey::Key::A],
        modifiers: vec![],
    };

    let is_pressed = Arc::new(Mutex::new(false));
    let is_p = Arc::clone(&is_pressed);
    hotkey
        .register(key.clone(), move || {
            let mut is_p = is_p.lock().unwrap();
            *is_p = true;
        })
        .unwrap();

    loop {
        let pressed = Arc::clone(&is_pressed);
        let mut pressed = pressed.lock().unwrap();

        if *pressed {
            hotkey.unregister(&key).unwrap();
            *pressed = false;
        }
    } // infinate loop for prevent main from existing
}