Add a keyboard key listener and when that key is pressed I want to remove that listener, i use this crates
Adding listener works fine
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
}
Remove the listener when clicking the key
hotkey
.register(key, || {
hotkey.unregister(&key).unwrap();
})
.unwrap();
it gave a compile error says
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`
Is there any way to fix this, access hotkey inside the closure ?
The register signature won't allow yourself to change "hotkey" even. First by "&mut self" constraint and second by the callback that's should be 'static
pub fn register<F>(&mut self, hotkey: Hotkey, callback: F) -> Result<()>
where
F: 'static + FnMut() + Send
An approach could be something like this
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.