winit/platform/
windows.rs

1//! # Windows
2//!
3//! The supported OS version is Windows 7 or higher, though Windows 10 is
4//! tested regularly.
5use std::borrow::Borrow;
6use std::ffi::c_void;
7use std::path::Path;
8
9use crate::dpi::PhysicalSize;
10use crate::event::DeviceId;
11use crate::event_loop::EventLoopBuilder;
12use crate::monitor::MonitorHandle;
13use crate::window::{BadIcon, Icon, Window, WindowAttributes};
14
15/// Window Handle type used by Win32 API
16pub type HWND = isize;
17/// Menu Handle type used by Win32 API
18pub type HMENU = isize;
19/// Monitor Handle type used by Win32 API
20pub type HMONITOR = isize;
21
22/// Describes a system-drawn backdrop material of a window.
23///
24/// For a detailed explanation, see [`DWM_SYSTEMBACKDROP_TYPE docs`].
25///
26/// [`DWM_SYSTEMBACKDROP_TYPE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum BackdropType {
29    /// Corresponds to `DWMSBT_AUTO`.
30    ///
31    /// Usually draws a default backdrop effect on the title bar.
32    #[default]
33    Auto = 0,
34
35    /// Corresponds to `DWMSBT_NONE`.
36    None = 1,
37
38    /// Corresponds to `DWMSBT_MAINWINDOW`.
39    ///
40    /// Draws the Mica backdrop material.
41    MainWindow = 2,
42
43    /// Corresponds to `DWMSBT_TRANSIENTWINDOW`.
44    ///
45    /// Draws the Background Acrylic backdrop material.
46    TransientWindow = 3,
47
48    /// Corresponds to `DWMSBT_TABBEDWINDOW`.
49    ///
50    /// Draws the Alt Mica backdrop material.
51    TabbedWindow = 4,
52}
53
54/// Describes a color used by Windows
55#[repr(transparent)]
56#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
57pub struct Color(u32);
58
59impl Color {
60    // Special constant only valid for the window border and therefore modeled using Option<Color>
61    // for user facing code
62    const NONE: Color = Color(0xfffffffe);
63    /// Use the system's default color
64    pub const SYSTEM_DEFAULT: Color = Color(0xffffffff);
65
66    /// Create a new color from the given RGB values
67    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
68        Self((r as u32) | ((g as u32) << 8) | ((b as u32) << 16))
69    }
70}
71
72impl Default for Color {
73    fn default() -> Self {
74        Self::SYSTEM_DEFAULT
75    }
76}
77
78/// Describes how the corners of a window should look like.
79///
80/// For a detailed explanation, see [`DWM_WINDOW_CORNER_PREFERENCE docs`].
81///
82/// [`DWM_WINDOW_CORNER_PREFERENCE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference
83#[repr(i32)]
84#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
85pub enum CornerPreference {
86    /// Corresponds to `DWMWCP_DEFAULT`.
87    ///
88    /// Let the system decide when to round window corners.
89    #[default]
90    Default = 0,
91
92    /// Corresponds to `DWMWCP_DONOTROUND`.
93    ///
94    /// Never round window corners.
95    DoNotRound = 1,
96
97    /// Corresponds to `DWMWCP_ROUND`.
98    ///
99    /// Round the corners, if appropriate.
100    Round = 2,
101
102    /// Corresponds to `DWMWCP_ROUNDSMALL`.
103    ///
104    /// Round the corners if appropriate, with a small radius.
105    RoundSmall = 3,
106}
107
108/// A wrapper around a [`Window`] that ignores thread-specific window handle limitations.
109///
110/// See [`WindowBorrowExtWindows::any_thread`] for more information.
111#[derive(Debug)]
112pub struct AnyThread<W>(W);
113
114impl<W: Borrow<Window>> AnyThread<W> {
115    /// Get a reference to the inner window.
116    #[inline]
117    pub fn get_ref(&self) -> &Window {
118        self.0.borrow()
119    }
120
121    /// Get a reference to the inner object.
122    #[inline]
123    pub fn inner(&self) -> &W {
124        &self.0
125    }
126
127    /// Unwrap and get the inner window.
128    #[inline]
129    pub fn into_inner(self) -> W {
130        self.0
131    }
132}
133
134impl<W: Borrow<Window>> AsRef<Window> for AnyThread<W> {
135    fn as_ref(&self) -> &Window {
136        self.get_ref()
137    }
138}
139
140impl<W: Borrow<Window>> Borrow<Window> for AnyThread<W> {
141    fn borrow(&self) -> &Window {
142        self.get_ref()
143    }
144}
145
146impl<W: Borrow<Window>> std::ops::Deref for AnyThread<W> {
147    type Target = Window;
148
149    fn deref(&self) -> &Self::Target {
150        self.get_ref()
151    }
152}
153
154#[cfg(feature = "rwh_06")]
155impl<W: Borrow<Window>> rwh_06::HasWindowHandle for AnyThread<W> {
156    fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
157        // SAFETY: The top level user has asserted this is only used safely.
158        unsafe { self.get_ref().window_handle_any_thread() }
159    }
160}
161
162/// Additional methods on `EventLoop` that are specific to Windows.
163pub trait EventLoopBuilderExtWindows {
164    /// Whether to allow the event loop to be created off of the main thread.
165    ///
166    /// By default, the window is only allowed to be created on the main
167    /// thread, to make platform compatibility easier.
168    ///
169    /// # `Window` caveats
170    ///
171    /// Note that any `Window` created on the new thread will be destroyed when the thread
172    /// terminates. Attempting to use a `Window` after its parent thread terminates has
173    /// unspecified, although explicitly not undefined, behavior.
174    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
175
176    /// Whether to enable process-wide DPI awareness.
177    ///
178    /// By default, `winit` will attempt to enable process-wide DPI awareness. If
179    /// that's undesirable, you can disable it with this function.
180    ///
181    /// # Example
182    ///
183    /// Disable process-wide DPI awareness.
184    ///
185    /// ```
186    /// use winit::event_loop::EventLoopBuilder;
187    /// #[cfg(target_os = "windows")]
188    /// use winit::platform::windows::EventLoopBuilderExtWindows;
189    ///
190    /// let mut builder = EventLoopBuilder::new();
191    /// #[cfg(target_os = "windows")]
192    /// builder.with_dpi_aware(false);
193    /// # if false { // We can't test this part
194    /// let event_loop = builder.build();
195    /// # }
196    /// ```
197    fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self;
198
199    /// A callback to be executed before dispatching a win32 message to the window procedure.
200    /// Return true to disable winit's internal message dispatching.
201    ///
202    /// # Example
203    ///
204    /// ```
205    /// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG};
206    /// use winit::event_loop::EventLoopBuilder;
207    /// #[cfg(target_os = "windows")]
208    /// use winit::platform::windows::EventLoopBuilderExtWindows;
209    ///
210    /// let mut builder = EventLoopBuilder::new();
211    /// #[cfg(target_os = "windows")]
212    /// builder.with_msg_hook(|msg|{
213    ///     let msg = msg as *const MSG;
214    /// #   let accels: Vec<ACCEL> = Vec::new();
215    ///     let translated = unsafe {
216    ///         TranslateAcceleratorW(
217    ///             (*msg).hwnd,
218    ///             CreateAcceleratorTableW(accels.as_ptr() as _, 1),
219    ///             msg,
220    ///         ) == 1
221    ///     };
222    ///     translated
223    /// });
224    /// ```
225    fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self
226    where
227        F: FnMut(*const c_void) -> bool + 'static;
228}
229
230impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> {
231    #[inline]
232    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
233        self.platform_specific.any_thread = any_thread;
234        self
235    }
236
237    #[inline]
238    fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self {
239        self.platform_specific.dpi_aware = dpi_aware;
240        self
241    }
242
243    #[inline]
244    fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self
245    where
246        F: FnMut(*const c_void) -> bool + 'static,
247    {
248        self.platform_specific.msg_hook = Some(Box::new(callback));
249        self
250    }
251}
252
253/// Additional methods on `Window` that are specific to Windows.
254pub trait WindowExtWindows {
255    /// Enables or disables mouse and keyboard input to the specified window.
256    ///
257    /// A window must be enabled before it can be activated.
258    /// If an application has create a modal dialog box by disabling its owner window
259    /// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must
260    /// enable the owner window before destroying the dialog box.
261    /// Otherwise, another window will receive the keyboard focus and be activated.
262    ///
263    /// If a child window is disabled, it is ignored when the system tries to determine which
264    /// window should receive mouse messages.
265    ///
266    /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks>
267    /// and <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#disabled-windows>
268    fn set_enable(&self, enabled: bool);
269
270    /// This sets `ICON_BIG`. A good ceiling here is 256x256.
271    fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>);
272
273    /// Whether to show or hide the window icon in the taskbar.
274    fn set_skip_taskbar(&self, skip: bool);
275
276    /// Shows or hides the background drop shadow for undecorated windows.
277    ///
278    /// Enabling the shadow causes a thin 1px line to appear on the top of the window.
279    fn set_undecorated_shadow(&self, shadow: bool);
280
281    /// Sets system-drawn backdrop type.
282    ///
283    /// Requires Windows 11 build 22523+.
284    fn set_system_backdrop(&self, backdrop_type: BackdropType);
285
286    /// Sets the color of the window border.
287    ///
288    /// Supported starting with Windows 11 Build 22000.
289    fn set_border_color(&self, color: Option<Color>);
290
291    /// Sets the background color of the title bar.
292    ///
293    /// Supported starting with Windows 11 Build 22000.
294    fn set_title_background_color(&self, color: Option<Color>);
295
296    /// Sets the color of the window title.
297    ///
298    /// Supported starting with Windows 11 Build 22000.
299    fn set_title_text_color(&self, color: Color);
300
301    /// Sets the preferred style of the window corners.
302    ///
303    /// Supported starting with Windows 11 Build 22000.
304    fn set_corner_preference(&self, preference: CornerPreference);
305
306    /// Get the raw window handle for this [`Window`] without checking for thread affinity.
307    ///
308    /// Window handles in Win32 have a property called "thread affinity" that ties them to their
309    /// origin thread. Some operations can only happen on the window's origin thread, while others
310    /// can be called from any thread. For example, [`SetWindowSubclass`] is not thread safe while
311    /// [`GetDC`] is thread safe.
312    ///
313    /// In Rust terms, the window handle is `Send` sometimes but `!Send` other times.
314    ///
315    /// Therefore, in order to avoid confusing threading errors, [`Window`] only returns the
316    /// window handle when the [`window_handle`] function is called from the thread that created
317    /// the window. In other cases, it returns an [`Unavailable`] error.
318    ///
319    /// However in some cases you may already know that you are using the window handle for
320    /// operations that are guaranteed to be thread-safe. In which case this function aims
321    /// to provide an escape hatch so these functions are still accessible from other threads.
322    ///
323    /// # Safety
324    ///
325    /// It is the responsibility of the user to only pass the window handle into thread-safe
326    /// Win32 APIs.
327    ///
328    /// [`SetWindowSubclass`]: https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-setwindowsubclass
329    /// [`GetDC`]: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc
330    /// [`Window`]: crate::window::Window
331    /// [`window_handle`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/trait.HasWindowHandle.html#tymethod.window_handle
332    /// [`Unavailable`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/enum.HandleError.html#variant.Unavailable
333    ///
334    /// ## Example
335    ///
336    /// ```no_run
337    /// # use winit::window::Window;
338    /// # fn scope(window: Window) {
339    /// use std::thread;
340    /// use winit::platform::windows::WindowExtWindows;
341    /// use winit::raw_window_handle::HasWindowHandle;
342    ///
343    /// // We can get the window handle on the current thread.
344    /// let handle = window.window_handle().unwrap();
345    ///
346    /// // However, on another thread, we can't!
347    /// thread::spawn(move || {
348    ///     assert!(window.window_handle().is_err());
349    ///
350    ///     // We can use this function as an escape hatch.
351    ///     let handle = unsafe { window.window_handle_any_thread().unwrap() };
352    /// });
353    /// # }
354    /// ```
355    #[cfg(feature = "rwh_06")]
356    unsafe fn window_handle_any_thread(
357        &self,
358    ) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError>;
359}
360
361impl WindowExtWindows for Window {
362    #[inline]
363    fn set_enable(&self, enabled: bool) {
364        self.window.set_enable(enabled)
365    }
366
367    #[inline]
368    fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
369        self.window.set_taskbar_icon(taskbar_icon)
370    }
371
372    #[inline]
373    fn set_skip_taskbar(&self, skip: bool) {
374        self.window.set_skip_taskbar(skip)
375    }
376
377    #[inline]
378    fn set_undecorated_shadow(&self, shadow: bool) {
379        self.window.set_undecorated_shadow(shadow)
380    }
381
382    #[inline]
383    fn set_system_backdrop(&self, backdrop_type: BackdropType) {
384        self.window.set_system_backdrop(backdrop_type)
385    }
386
387    #[inline]
388    fn set_border_color(&self, color: Option<Color>) {
389        self.window.set_border_color(color.unwrap_or(Color::NONE))
390    }
391
392    #[inline]
393    fn set_title_background_color(&self, color: Option<Color>) {
394        // The windows docs don't mention NONE as a valid options but it works in practice and is
395        // useful to circumvent the Windows option "Show accent color on title bars and
396        // window borders"
397        self.window.set_title_background_color(color.unwrap_or(Color::NONE))
398    }
399
400    #[inline]
401    fn set_title_text_color(&self, color: Color) {
402        self.window.set_title_text_color(color)
403    }
404
405    #[inline]
406    fn set_corner_preference(&self, preference: CornerPreference) {
407        self.window.set_corner_preference(preference)
408    }
409
410    #[cfg(feature = "rwh_06")]
411    unsafe fn window_handle_any_thread(
412        &self,
413    ) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
414        unsafe {
415            let handle = self.window.rwh_06_no_thread_check()?;
416
417            // SAFETY: The handle is valid in this context.
418            Ok(rwh_06::WindowHandle::borrow_raw(handle))
419        }
420    }
421}
422
423/// Additional methods for anything that dereference to [`Window`].
424///
425/// [`Window`]: crate::window::Window
426pub trait WindowBorrowExtWindows: Borrow<Window> + Sized {
427    /// Create an object that allows accessing the inner window handle in a thread-unsafe way.
428    ///
429    /// It is possible to call [`window_handle_any_thread`] to get around Windows's thread
430    /// affinity limitations. However, it may be desired to pass the [`Window`] into something
431    /// that requires the [`HasWindowHandle`] trait, while ignoring thread affinity limitations.
432    ///
433    /// This function wraps anything that implements `Borrow<Window>` into a structure that
434    /// uses the inner window handle as a mean of implementing [`HasWindowHandle`]. It wraps
435    /// `Window`, `&Window`, `Arc<Window>`, and other reference types.
436    ///
437    /// # Safety
438    ///
439    /// It is the responsibility of the user to only pass the window handle into thread-safe
440    /// Win32 APIs.
441    ///
442    /// [`window_handle_any_thread`]: WindowExtWindows::window_handle_any_thread
443    /// [`Window`]: crate::window::Window
444    /// [`HasWindowHandle`]: rwh_06::HasWindowHandle
445    unsafe fn any_thread(self) -> AnyThread<Self> {
446        AnyThread(self)
447    }
448}
449
450impl<W: Borrow<Window> + Sized> WindowBorrowExtWindows for W {}
451
452/// Additional methods on `WindowAttributes` that are specific to Windows.
453#[allow(rustdoc::broken_intra_doc_links)]
454pub trait WindowAttributesExtWindows {
455    /// Set an owner to the window to be created. Can be used to create a dialog box, for example.
456    /// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`.
457    /// Can be used in combination with
458    /// [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable] on the owner
459    /// window to create a modal dialog box.
460    ///
461    /// From MSDN:
462    /// - An owned window is always above its owner in the z-order.
463    /// - The system automatically destroys an owned window when its owner is destroyed.
464    /// - An owned window is hidden when its owner is minimized.
465    ///
466    /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
467    fn with_owner_window(self, parent: HWND) -> Self;
468
469    /// Sets a menu on the window to be created.
470    ///
471    /// Parent and menu are mutually exclusive; a child window cannot have a menu!
472    ///
473    /// The menu must have been manually created beforehand with [`CreateMenu`] or similar.
474    ///
475    /// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how
476    /// the menus look. If you use this, it is recommended that you combine it with
477    /// `with_theme(Some(Theme::Light))` to avoid a jarring effect.
478    #[cfg_attr(
479        windows_platform,
480        doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu"
481    )]
482    #[cfg_attr(not(windows_platform), doc = "[`CreateMenu`]: #only-available-on-windows")]
483    fn with_menu(self, menu: HMENU) -> Self;
484
485    /// This sets `ICON_BIG`. A good ceiling here is 256x256.
486    fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> Self;
487
488    /// This sets `WS_EX_NOREDIRECTIONBITMAP`.
489    fn with_no_redirection_bitmap(self, flag: bool) -> Self;
490
491    /// Enables or disables drag and drop support (enabled by default). Will interfere with other
492    /// crates that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED`
493    /// instead of `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still
494    /// attempt to initialize COM API regardless of this option. Currently only fullscreen mode
495    /// does that, but there may be more in the future. If you need COM API with
496    /// `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information.
497    fn with_drag_and_drop(self, flag: bool) -> Self;
498
499    /// Whether show or hide the window icon in the taskbar.
500    fn with_skip_taskbar(self, skip: bool) -> Self;
501
502    /// Customize the window class name.
503    fn with_class_name<S: Into<String>>(self, class_name: S) -> Self;
504
505    /// Shows or hides the background drop shadow for undecorated windows.
506    ///
507    /// The shadow is hidden by default.
508    /// Enabling the shadow causes a thin 1px line to appear on the top of the window.
509    fn with_undecorated_shadow(self, shadow: bool) -> Self;
510
511    /// Sets system-drawn backdrop type.
512    ///
513    /// Requires Windows 11 build 22523+.
514    fn with_system_backdrop(self, backdrop_type: BackdropType) -> Self;
515
516    /// This sets or removes `WS_CLIPCHILDREN` style.
517    fn with_clip_children(self, flag: bool) -> Self;
518
519    /// Sets the color of the window border.
520    ///
521    /// Supported starting with Windows 11 Build 22000.
522    fn with_border_color(self, color: Option<Color>) -> Self;
523
524    /// Sets the background color of the title bar.
525    ///
526    /// Supported starting with Windows 11 Build 22000.
527    fn with_title_background_color(self, color: Option<Color>) -> Self;
528
529    /// Sets the color of the window title.
530    ///
531    /// Supported starting with Windows 11 Build 22000.
532    fn with_title_text_color(self, color: Color) -> Self;
533
534    /// Sets the preferred style of the window corners.
535    ///
536    /// Supported starting with Windows 11 Build 22000.
537    fn with_corner_preference(self, corners: CornerPreference) -> Self;
538}
539
540impl WindowAttributesExtWindows for WindowAttributes {
541    #[inline]
542    fn with_owner_window(mut self, parent: HWND) -> Self {
543        self.platform_specific.owner = Some(parent);
544        self
545    }
546
547    #[inline]
548    fn with_menu(mut self, menu: HMENU) -> Self {
549        self.platform_specific.menu = Some(menu);
550        self
551    }
552
553    #[inline]
554    fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> Self {
555        self.platform_specific.taskbar_icon = taskbar_icon;
556        self
557    }
558
559    #[inline]
560    fn with_no_redirection_bitmap(mut self, flag: bool) -> Self {
561        self.platform_specific.no_redirection_bitmap = flag;
562        self
563    }
564
565    #[inline]
566    fn with_drag_and_drop(mut self, flag: bool) -> Self {
567        self.platform_specific.drag_and_drop = flag;
568        self
569    }
570
571    #[inline]
572    fn with_skip_taskbar(mut self, skip: bool) -> Self {
573        self.platform_specific.skip_taskbar = skip;
574        self
575    }
576
577    #[inline]
578    fn with_class_name<S: Into<String>>(mut self, class_name: S) -> Self {
579        self.platform_specific.class_name = class_name.into();
580        self
581    }
582
583    #[inline]
584    fn with_undecorated_shadow(mut self, shadow: bool) -> Self {
585        self.platform_specific.decoration_shadow = shadow;
586        self
587    }
588
589    #[inline]
590    fn with_system_backdrop(mut self, backdrop_type: BackdropType) -> Self {
591        self.platform_specific.backdrop_type = backdrop_type;
592        self
593    }
594
595    #[inline]
596    fn with_clip_children(mut self, flag: bool) -> Self {
597        self.platform_specific.clip_children = flag;
598        self
599    }
600
601    #[inline]
602    fn with_border_color(mut self, color: Option<Color>) -> Self {
603        self.platform_specific.border_color = Some(color.unwrap_or(Color::NONE));
604        self
605    }
606
607    #[inline]
608    fn with_title_background_color(mut self, color: Option<Color>) -> Self {
609        self.platform_specific.title_background_color = Some(color.unwrap_or(Color::NONE));
610        self
611    }
612
613    #[inline]
614    fn with_title_text_color(mut self, color: Color) -> Self {
615        self.platform_specific.title_text_color = Some(color);
616        self
617    }
618
619    #[inline]
620    fn with_corner_preference(mut self, corners: CornerPreference) -> Self {
621        self.platform_specific.corner_preference = Some(corners);
622        self
623    }
624}
625
626/// Additional methods on `MonitorHandle` that are specific to Windows.
627pub trait MonitorHandleExtWindows {
628    /// Returns the name of the monitor adapter specific to the Win32 API.
629    fn native_id(&self) -> String;
630
631    /// Returns the handle of the monitor - `HMONITOR`.
632    fn hmonitor(&self) -> HMONITOR;
633}
634
635impl MonitorHandleExtWindows for MonitorHandle {
636    #[inline]
637    fn native_id(&self) -> String {
638        self.inner.native_identifier()
639    }
640
641    #[inline]
642    fn hmonitor(&self) -> HMONITOR {
643        self.inner.hmonitor()
644    }
645}
646
647/// Additional methods on `DeviceId` that are specific to Windows.
648pub trait DeviceIdExtWindows {
649    /// Returns an identifier that persistently refers to this specific device.
650    ///
651    /// Will return `None` if the device is no longer available.
652    fn persistent_identifier(&self) -> Option<String>;
653}
654
655impl DeviceIdExtWindows for DeviceId {
656    #[inline]
657    fn persistent_identifier(&self) -> Option<String> {
658        self.0.persistent_identifier()
659    }
660}
661
662/// Additional methods on `Icon` that are specific to Windows.
663pub trait IconExtWindows: Sized {
664    /// Create an icon from a file path.
665    ///
666    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
667    /// icon size from the file.
668    ///
669    /// In cases where the specified size does not exist in the file, Windows may perform scaling
670    /// to get an icon of the desired size.
671    fn from_path<P: AsRef<Path>>(path: P, size: Option<PhysicalSize<u32>>)
672        -> Result<Self, BadIcon>;
673
674    /// Create an icon from a resource embedded in this executable or library.
675    ///
676    /// Specify `size` to load a specific icon size from the file, or `None` to load the default
677    /// icon size from the file.
678    ///
679    /// In cases where the specified size does not exist in the file, Windows may perform scaling
680    /// to get an icon of the desired size.
681    fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>;
682}
683
684impl IconExtWindows for Icon {
685    fn from_path<P: AsRef<Path>>(
686        path: P,
687        size: Option<PhysicalSize<u32>>,
688    ) -> Result<Self, BadIcon> {
689        let win_icon = crate::platform_impl::WinIcon::from_path(path, size)?;
690        Ok(Icon { inner: win_icon })
691    }
692
693    fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
694        let win_icon = crate::platform_impl::WinIcon::from_resource(ordinal, size)?;
695        Ok(Icon { inner: win_icon })
696    }
697}