Narsil / rdev

Simple library to listen and send events to keyboard and mouse (MacOS, Windows, Linux)
MIT License
465 stars 117 forks source link

No mouse move event emitted while mouse is down #136

Open HuakunShen opened 2 weeks ago

HuakunShen commented 2 weeks ago

When left mouse button is down, mouse move events are no longer detected.

How can this be solved?

I am trying to detect mouse movements while holding and moving a file.

qzd1989 commented 1 week ago

you are right, I only can get the position when button pressed, but I can't get the position if mouse doesn't move after button released.

use rdev::{listen, Button, Event, EventType};
use std::sync::{Arc, Mutex};
use std::thread::{self, spawn};
use std::time::Duration;

fn main() {
    let mouse_state = Arc::new(Mutex::new(MouseState::new()));
    let mouse_state_clone = Arc::clone(&mouse_state);
    spawn(|| {
        if let Err(error) = listen(move |event| callback(event, &mouse_state_clone)) {
            println!("Error: {:?}", error)
        }
    });
    thread::sleep(Duration::from_secs(3600));
}

#[derive(Debug)]
pub struct MouseState {
    pub last_position: Option<(f64, f64)>,
}

impl MouseState {
    fn new() -> Self {
        MouseState {
            last_position: None,
        }
    }
}
fn callback(event: Event, mouse_state: &Arc<Mutex<MouseState>>) {
    match event.event_type {
        EventType::ButtonPress(button) => {
            let mouse_state = mouse_state.lock().unwrap();
            if let Some(last_position) = mouse_state.last_position {
                if button == Button::Left {
                    println!("position is :{}, {}", last_position.0, last_position.1);
                }
            }
        }
        EventType::ButtonRelease(button) => {
            if button == Button::Left {
                //I can't get the position if mouse doesn't move after button released.
            }
        }
        EventType::MouseMove { x, y } => {
            let mut mouse_state = mouse_state.lock().unwrap();
            mouse_state.last_position = Some((x, y));
        }
        _ => {}
    }
}
qzd1989 commented 1 week ago

I have pull something new for this issue, the EventType will return position when mouse button pressed or released. see here: https://github.com/Narsil/rdev/pull/138