Search code examples
c++windows-runtimewinrt-xamlc++-winrtwinui-3

How to get the compositor instance while handling XamlCompositionBrushBase.OnConnected in a WinUI-3 desktop app


Following this c++ example i'm trying to create a custom brush in a WinUI 3 desktop application but i cannot find out how to get a compositor instance from within the OnConnected Method. The example uses

Microsoft::UI::Xaml::Window::Current().Compositor()

but Current (and CoreWindow) are always null for desktop apps.

How can i get the compositor instance needed to create brushes?


Solution

  • Ok, as often it gets easy as soon as the matching documentation is found:

    In XAML apps, we recommend that you call ElementCompositionPreview.GetElementVisual(UIElement) to get a Composition Visual, and get the Compositor from the visual's Compositor property. In cases where you don't have access to a UIElement (for example, if you create a CompositionBrush in a class library), you can call CompositionTarget.GetCompositorForCurrentThread to get the Compositor instead.

    Related issue.

    Related Issue.