Narsil / rdev

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

How to run listener in a thread and stop it? #133

Open HuakunShen opened 4 months ago

HuakunShen commented 4 months ago

How to run the listener in a thread and be able to cancel it some time later?

I tried to use tokio join handle's abort() method but doesn't work.

I am on Mac and in the source code I saw that native APIs were used instead of rust loop, I guess that's why abort() won't work.

Is there any way to do that?

use rdev::{listen, Event};

fn callback(event: Event) {
    println!("My callback {:?}", event);
}

#[tokio::main]
async fn main() {
    let join_handle = tokio::spawn(async move {
        if let Err(error) = listen(callback) {
            println!("Error: {:?}", error)
        }

    });
    tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
    println!("aborting join handle  ");
    join_handle.abort();
    println!("aborted");
    tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
}
edraze commented 3 months ago

See here(https://github.com/Narsil/rdev/issues/72) for more details

qzd1989 commented 3 months ago

https://github.com/Narsil/rdev/pull/137

I pushed some code to provide stop_listen function on macos~