3

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?

IInspectable
  • 46,945
  • 8
  • 85
  • 181
ridilculous
  • 624
  • 3
  • 16

2 Answers2

1

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

Roy Li - MSFT
  • 8,043
  • 1
  • 7
  • 13
  • 2
    The question is tagged [tag:c++-winrt]. The code here isn't C++. – IInspectable Oct 04 '22 at 07:55
  • I guess [`Window.Current()`](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.window.current?view=windows-app-sdk-1.1) might be an alternative but MS writes _Desktop apps always return null_. – ridilculous Oct 04 '22 at 10:41
  • @ridilculous Yes, but your app is not a UWP application, right? As I mentioned, if you are not a UWP application, you could only get the handle of the window. – Roy Li - MSFT Oct 05 '22 at 03:21
  • I need the actual instance so that i can cast to its projection or implementation type. Or is there a way to get the instance afterwards using the `HWND`? – ridilculous Oct 05 '22 at 06:28
  • @ridilculous hello, did you find an alternative? – Jacques Dec 14 '22 at 19:19
  • @Jacques no generic one; luckily i could store it explicitly somewhere and just get it from there but it's not a nice solution. – ridilculous Dec 16 '22 at 10:20
  • Thank you. I'd be glad to see it, I can't find any solution at all. – Jacques Dec 16 '22 at 13:27
0

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'.

ACGMN
  • 9
  • 3