I am trying to use the acrylic brush in WinUI 3, I read the documentation and it says that I must create an auxiliary class WindowsSystemDispatcherQueueHelper
.
I have followed the process but it throws an exception.
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Composition;
using Microsoft.UI.Xaml;
using Microsoft.UI;
using WinRT;
namespace Alessia.Helpers
{
static class BackdropService
{
public static bool TrySetAcrylicBackdrop(Window window)
{
if (DesktopAcrylicController.IsSupported())
{
m_sdqHelper ??= new();
m_sdqHelper.EnsureWindowsSystemDispatcherQueueController();
// Hooking up the policy object
m_configurationSource ??= new();
window.Activated += OnWindowActivated;
window.Closed += OnWindowClosed;
(window.Content as FrameworkElement).ActualThemeChanged += OnActualThemeChanged;
// Initial configuration state.
m_configurationSource.IsInputActive = true;
SetConfigurationSourceTheme(window.Content as FrameworkElement);
m_acrylicController ??= new()
{
TintColor = Colors.Red
};
// Enable the system backdrop.
// Note: Be sure to have "using WinRT;" to support the Window.As<...>() call.
m_acrylicController.AddSystemBackdropTarget(window.As<ICompositionSupportsSystemBackdrop>());
m_acrylicController.SetSystemBackdropConfiguration(m_configurationSource);
return true; // succeeded
}
return false; // Acrylic is not supported on this system
}
}
}
And the auxiliary class
using System.Runtime.InteropServices;
namespace Alessia.Helpers
{
sealed class WindowsSystemDispatcherQueueHelper
{
[StructLayout(LayoutKind.Sequential)]
struct DispatcherQueueOptions
{
internal int dwSize;
internal int threadType;
internal int apartmentType;
}
[DllImport("CoreMessaging.dll")]
private static extern int CreateDispatcherQueueController([In] DispatcherQueueOptions options, [In, Out, MarshalAs(UnmanagedType.IUnknown)] ref object dispatcherQueueController);
public void EnsureWindowsSystemDispatcherQueueController()
{
if (Windows.System.DispatcherQueue.GetForCurrentThread() != null)
// one already exists, so we'll just use it.
return;
if (m_dispatcherQueueController == null)
{
DispatcherQueueOptions options;
options.dwSize = Marshal.SizeOf(typeof(DispatcherQueueOptions));
options.threadType = 2; // DQTYPE_THREAD_CURRENT
options.apartmentType = 2; // DQTAT_COM_STA
_ = CreateDispatcherQueueController(options, ref m_dispatcherQueueController);
}
}
object m_dispatcherQueueController = null;
}
}
The exception is in the first class, in the line m_acrylicController.AddSystemBackdropTarget(window.As<ICompositionSupportsSystemBackdrop>());