Skip to main content

window_observer/platform_impl/windows/
observer.rs

1use tokio::sync::oneshot;
2use wineventhook::WindowEventHook;
3
4use crate::{Error, EventTx};
5
6use super::hook_task::make_wineventhook_task;
7
8/// Observes window events on the Windows platform by using [wineventhook].
9pub struct WindowsWindowObserver {
10    hook: WindowEventHook,
11    done_rx: oneshot::Receiver<()>,
12}
13
14impl WindowsWindowObserver {
15    /// Starts observing window events for a specific process ID.
16    pub async fn start(
17        pid: u32,
18        event_tx: EventTx,
19        event_filter: crate::EventFilter,
20    ) -> Result<Self, Error> {
21        if pid == 0 {
22            return Err(Error::InvalidProcessId(pid));
23        }
24
25        let (hook, done_rx) = make_wineventhook_task(pid, event_tx, event_filter).await?;
26
27        Ok(Self { hook, done_rx })
28    }
29
30    /// Stops observing window events.
31    pub async fn stop(self) -> Result<(), Error> {
32        self.hook
33            .unhook()
34            .await
35            .map_err(super::error::WindowsError::from)?;
36
37        self.done_rx
38            .await
39            .map_err(super::error::WindowsError::from)?;
40
41        Ok(())
42    }
43
44    /// Retrieves the underlying [`WindowEventHook`].
45    pub fn hook(&self) -> &WindowEventHook {
46        &self.hook
47    }
48}