obv-mikhail / InputBot

Rust library for creating global hotkeys, and simulating inputs
MIT License
421 stars 74 forks source link

Some way to stop listening for events. #68

Closed kumorig closed 2 years ago

kumorig commented 2 years ago

Sorry if this is more of a help request than an actual issue.

Is there really no way to stop listening for events? Shouldn´t there be a way to lets say inputbot::stop_handle_input_events();?

At the moment I do something like this:

    let t = thread::spawn(move || {
        inputbot::MouseButton::LeftButton.bind(move || {
            let pos = inputbot::MouseCursor::pos();
            if let Ok(element) = automation.element_from_point(Point::new(pos.0, pos.1)) {
                state.lock().unwrap().pick_mode = PickMode::Selected(element.get_hwnd());                
                inputbot::MouseButton::LeftButton.unbind();
            }
        });
        inputbot::handle_input_events();
    });

    // wait until the user has picked an element
    while app_state.lock().unwrap().pick_mode == PickMode::Pick {
        thread::sleep(Duration::from_millis(100));
    }

    // End the thread? how?
    drop(t);

So I unbind what I can, and drop the thread. I do however assume that the thread lives on in the background (!) I think I could have just one thread living in the background for the duration of my program, and do some rx/tx stuff instead so I can reuse the same thread., but I would still expect it to be possible to simply stop "handle_input_events" at some point.

So to me (I'm still new at this), the lack of this functionality is somewhat startling. But it could of course just mean I'm going about things the wrong way, or that I've missed something obvious.

Any clarification in the matter would be highly appreciated, thanks!

robertwayne commented 2 years ago

Looking at the code for handle_input_events, the loop exits if both KEYBD_BINDS and MOUSE_BINDS are empty. So, as long as you've unbound everything, then it will accomplish your goal.

This would probably still be a useful helper function to have.

With regards to threads, it's not safe to "kill" threads in any context. So, once those hashmaps are emptied, there's nothing else to do.

kumorig commented 2 years ago

Oh, I knew I was missing something! That's awesome. Hey thanks for taking the time to answer! =)