Files
Shrlalgo.RvKits/WPFluent/Controls/Window/WindowBackdrop.cs
2025-05-05 17:04:06 +08:00

103 lines
2.9 KiB
C#

using System.Runtime.InteropServices;
using WPFluent.Appearance;
using WPFluent.Interop;
// ReSharper disable once CheckNamespace
namespace WPFluent.Controls;
/// <summary>
/// Applies the chosen backdrop effect to the selected window.
/// </summary>
public static class WindowBackdrop
{
private static SolidColorBrush GetFallbackBackgroundBrush()
{
return ThemeManager.GetAppTheme() switch
{
ThemeType.Unknow => new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFA, 0xEF)),
ThemeType.Light => new SolidColorBrush(Color.FromArgb(0xFF, 0xFA, 0xFA, 0xFA)),
ThemeType.Dark => new SolidColorBrush(Color.FromArgb(0xFF, 0x20, 0x20, 0x20)),
_ => 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;
}
/// <summary>
/// Tries to remove background from <see cref="Window"/> and it's composition area.
/// </summary>
/// <param name="window">Window to manipulate.</param>
/// <returns><see langword="true"/> if operation was successful.</returns>
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;
}
}