Reputation: 792
I'm trying to get the Window
instance which is hosting a UIElement
instance in WinUI 3.
There's a helper method in the Window class in .NET (see this thread) but i cannot find something similar for C++/WinRT.
I tried VisualTreeHelper
as some suggested but it doesn't help here; none of the parents were of type winrt::Microsoft::UI::Xaml::Window
.
Is it possible to get the hosting Window
of a dependency object?
Upvotes: 3
Views: 890
Reputation: 19
This problem has long puzzled me. And I find this API available since winrt-18362. Unfortunately, the AppWindow needed here is under namespace Windows.UI.Xaml.Hosting rather than Microsoft.UI.Windowing. The later one is easy to get from a HWND. BTW, I've also tried to store the Window instance somewhere but always failed with some error related to its constructor. Then, I finally achieved it by storing it as a static const reference and reassigning the variable through its pointer.
I just find an alternative method to manage Window instances here. This would help us get window from any known custom implementation type. But there would be link error with no initialization or compile error due to no 'inline'.
Upvotes: 0
Reputation: 8666
If it is a UWP application, each UI thread already has a Window that can be retrieved using the static Window.Current property.
If it is a C++/WinRT WinUI3 in Desktop application, Window implements IWindowNative
to enable interop through the Window's HWND (WindowHandle). You could get the handle of the Window and do what you want. Like:
// Get the current window's HWND by passing in the Window object
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
For more information, please check: Window Class-Windows App SDK
Upvotes: 1