window_focus.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //! Listen for window focus events using a wry event handler
  2. //!
  3. //! This example shows how to use the use_wry_event_handler hook to listen for window focus events.
  4. //! We can intercept any Wry event, but in this case we're only interested in the WindowEvent::Focused event.
  5. //!
  6. //! This lets you do things like backgrounding tasks, pausing animations, or changing the UI when the window is focused or not.
  7. use dioxus::desktop::tao::event::Event as WryEvent;
  8. use dioxus::desktop::tao::event::WindowEvent;
  9. use dioxus::desktop::use_wry_event_handler;
  10. use dioxus::desktop::{Config, WindowCloseBehaviour};
  11. use dioxus::prelude::*;
  12. fn main() {
  13. dioxus::LaunchBuilder::desktop()
  14. .with_cfg(Config::new().with_close_behaviour(WindowCloseBehaviour::CloseWindow))
  15. .launch(app)
  16. }
  17. fn app() -> Element {
  18. let mut focused = use_signal(|| true);
  19. use_wry_event_handler(move |event, _| {
  20. if let WryEvent::WindowEvent {
  21. event: WindowEvent::Focused(new_focused),
  22. ..
  23. } = event
  24. {
  25. focused.set(*new_focused)
  26. }
  27. });
  28. rsx! {
  29. div { width: "100%", height: "100%", display: "flex", flex_direction: "column", align_items: "center",
  30. if focused() {
  31. "This window is focused!"
  32. } else {
  33. "This window is not focused!"
  34. }
  35. }
  36. }
  37. }