using System.Runtime.InteropServices;
using WPFluent.Appearance;
using WPFluent.Interop;
// ReSharper disable once CheckNamespace
namespace WPFluent.Controls;
///
/// Applies the chosen backdrop effect to the selected window.
///
public static class WindowBackdrop
{
private static SolidColorBrush GetFallbackBackgroundBrush()
{
return ApplicationThemeManager.GetAppTheme() switch
{
ApplicationTheme.HC1 => new SolidColorBrush(Color.FromArgb(0xFF, 0x2D, 0x32, 0x36)),
ApplicationTheme.HC2 => new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x00, 0x00)),
ApplicationTheme.HCBlack => new SolidColorBrush(Color.FromArgb(0xFF, 0x20, 0x20, 0x20)),
ApplicationTheme.HCWhite => new SolidColorBrush(Color.FromArgb(0xFF, 0x20, 0x20, 0x20)),
ApplicationTheme.Unknown => new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFA, 0xEF)),
ApplicationTheme.Dark => new SolidColorBrush(Color.FromArgb(0xFF, 0x20, 0x20, 0x20)),
ApplicationTheme.Light => new SolidColorBrush(Color.FromArgb(0xFF, 0xFA, 0xFA, 0xFA)),
_ => new SolidColorBrush(Color.FromArgb(0xFF, 0xFA, 0xFA, 0xFA)),
};
}
/*private static bool ApplyLegacyAcrylicBackdrop(IntPtr hWnd)
{
throw new NotImplementedException();
}*/
private static bool RestoreContentBackground(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
{
return false;
}
if (!User32.IsWindow(hWnd))
{
return false;
}
var windowSource = HwndSource.FromHwnd(hWnd);
// Restore client area background
if (windowSource?.Handle != IntPtr.Zero && windowSource?.CompositionTarget != null)
{
windowSource.CompositionTarget.BackgroundColor = SystemColors.WindowColor;
}
if (windowSource?.RootVisual is System.Windows.Window window)
{
var backgroundBrush = window.Resources["ApplicationBackgroundBrush"];
// Manual fallback
if (backgroundBrush is not SolidColorBrush)
{
backgroundBrush = GetFallbackBackgroundBrush();
}
window.Background = (SolidColorBrush)backgroundBrush;
}
return true;
}
///
/// Tries to remove background from and it's composition area.
///
/// Window to manipulate.
/// if operation was successful.
public static bool RemoveBackground(System.Windows.Window? window)
{
if (window is null)
{
return false;
}
// Remove background from visual root
window.SetCurrentValue(System.Windows.Controls.Control.BackgroundProperty, Brushes.Transparent);
IntPtr windowHandle = new WindowInteropHelper(window).Handle;
if (windowHandle == IntPtr.Zero)
{
return false;
}
var windowSource = HwndSource.FromHwnd(windowHandle);
// Remove background from client area
if (windowSource?.Handle != IntPtr.Zero && windowSource?.CompositionTarget != null)
{
windowSource.CompositionTarget.BackgroundColor = Colors.Transparent;
}
return true;
}
}