/ src / settings-ui / Settings.UI / Helpers / WindowHelper.cs
WindowHelper.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System;
 6  using System.IO;
 7  using System.Runtime.InteropServices;
 8  using System.Text.Json;
 9  using Microsoft.PowerToys.Settings.UI.SerializationContext;
10  using Microsoft.UI.Xaml;
11  
12  namespace Microsoft.PowerToys.Settings.UI.Helpers
13  {
14      internal sealed class WindowHelper
15      {
16          private static string _placementPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\PowerToys\settings-placement.json");
17  
18          public static WINDOWPLACEMENT DeserializePlacementOrDefault(IntPtr handle)
19          {
20              try
21              {
22                  var json = File.ReadAllText(_placementPath);
23                  var placement = JsonSerializer.Deserialize<WINDOWPLACEMENT>(json, SourceGenerationContextContext.Default.WINDOWPLACEMENT);
24  
25                  placement.Length = Marshal.SizeOf<WINDOWPLACEMENT>();
26                  placement.Flags = 0;
27                  placement.ShowCmd = (placement.ShowCmd == NativeMethods.SW_SHOWMAXIMIZED) ? NativeMethods.SW_SHOWMAXIMIZED : NativeMethods.SW_SHOWNORMAL;
28                  return placement;
29              }
30              catch (Exception)
31              {
32              }
33  
34              _ = NativeMethods.GetWindowPlacement(handle, out var defaultPlacement);
35              return defaultPlacement;
36          }
37  
38          public static void SerializePlacement(IntPtr handle)
39          {
40              _ = NativeMethods.GetWindowPlacement(handle, out var placement);
41              try
42              {
43                  var json = JsonSerializer.Serialize(placement, SourceGenerationContextContext.Default.WINDOWPLACEMENT);
44                  File.WriteAllText(_placementPath, json);
45              }
46              catch (Exception)
47              {
48              }
49          }
50  
51          public static void SetTheme(Window window, ElementTheme theme)
52          {
53              if (window.Content is FrameworkElement rootElement)
54              {
55                  rootElement.RequestedTheme = theme;
56              }
57          }
58      }
59  }