SystemParameters2.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*************************************************************************************
  2. Extended WPF Toolkit
  3. Copyright (C) 2007-2013 Xceed Software Inc.
  4. This program is provided to you under the terms of the Microsoft Public
  5. License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
  6. For more features, controls, and fast professional support,
  7. pick up the Plus Edition at http://xceed.com/wpf_toolkit
  8. Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
  9. ***********************************************************************************/
  10. /**************************************************************************\
  11. Copyright Microsoft Corporation. All Rights Reserved.
  12. \**************************************************************************/
  13. namespace Microsoft.Windows.Shell
  14. {
  15. using System;
  16. using System.Collections.Generic;
  17. using System.ComponentModel;
  18. using System.Diagnostics.CodeAnalysis;
  19. using System.Runtime.InteropServices;
  20. using System.Windows;
  21. using System.Windows.Media;
  22. using Standard;
  23. [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
  24. public class SystemParameters2 : INotifyPropertyChanged
  25. {
  26. private delegate void _SystemMetricUpdate(IntPtr wParam, IntPtr lParam);
  27. [ThreadStatic]
  28. private static SystemParameters2 _threadLocalSingleton;
  29. private MessageWindow _messageHwnd;
  30. private bool _isGlassEnabled;
  31. private Color _glassColor;
  32. private SolidColorBrush _glassColorBrush;
  33. private Thickness _windowResizeBorderThickness;
  34. private Thickness _windowNonClientFrameThickness;
  35. private double _captionHeight;
  36. private Size _smallIconSize;
  37. private string _uxThemeName;
  38. private string _uxThemeColor;
  39. private bool _isHighContrast;
  40. private CornerRadius _windowCornerRadius;
  41. private Rect _captionButtonLocation;
  42. private readonly Dictionary<WM, List<_SystemMetricUpdate>> _UpdateTable;
  43. #region Initialization and Update Methods
  44. // Most properties exposed here have a way of being queried directly
  45. // and a way of being notified of updates via a window message.
  46. // This region is a grouping of both, for each of the exposed properties.
  47. private void _InitializeIsGlassEnabled()
  48. {
  49. IsGlassEnabled = NativeMethods.DwmIsCompositionEnabled();
  50. }
  51. private void _UpdateIsGlassEnabled(IntPtr wParam, IntPtr lParam)
  52. {
  53. // Neither the wParam or lParam are used in this case.
  54. _InitializeIsGlassEnabled();
  55. }
  56. private void _InitializeGlassColor()
  57. {
  58. bool isOpaque;
  59. uint color;
  60. NativeMethods.DwmGetColorizationColor(out color, out isOpaque);
  61. color |= isOpaque ? 0xFF000000 : 0;
  62. WindowGlassColor = Utility.ColorFromArgbDword(color);
  63. var glassBrush = new SolidColorBrush(WindowGlassColor);
  64. glassBrush.Freeze();
  65. WindowGlassBrush = glassBrush;
  66. }
  67. private void _UpdateGlassColor(IntPtr wParam, IntPtr lParam)
  68. {
  69. bool isOpaque = lParam != IntPtr.Zero;
  70. uint color = unchecked((uint)(int)wParam.ToInt64());
  71. color |= isOpaque ? 0xFF000000 : 0;
  72. WindowGlassColor = Utility.ColorFromArgbDword(color);
  73. var glassBrush = new SolidColorBrush(WindowGlassColor);
  74. glassBrush.Freeze();
  75. WindowGlassBrush = glassBrush;
  76. }
  77. private void _InitializeCaptionHeight()
  78. {
  79. Point ptCaption = new Point(0, NativeMethods.GetSystemMetrics(SM.CYCAPTION));
  80. WindowCaptionHeight = DpiHelper.DevicePixelsToLogical(ptCaption).Y;
  81. }
  82. private void _UpdateCaptionHeight(IntPtr wParam, IntPtr lParam)
  83. {
  84. _InitializeCaptionHeight();
  85. }
  86. private void _InitializeWindowResizeBorderThickness()
  87. {
  88. Size frameSize = new Size(
  89. NativeMethods.GetSystemMetrics(SM.CXSIZEFRAME),
  90. NativeMethods.GetSystemMetrics(SM.CYSIZEFRAME));
  91. Size frameSizeInDips = DpiHelper.DeviceSizeToLogical(frameSize);
  92. WindowResizeBorderThickness = new Thickness(frameSizeInDips.Width, frameSizeInDips.Height, frameSizeInDips.Width, frameSizeInDips.Height);
  93. }
  94. private void _UpdateWindowResizeBorderThickness(IntPtr wParam, IntPtr lParam)
  95. {
  96. _InitializeWindowResizeBorderThickness();
  97. }
  98. private void _InitializeWindowNonClientFrameThickness()
  99. {
  100. Size frameSize = new Size(
  101. NativeMethods.GetSystemMetrics(SM.CXSIZEFRAME),
  102. NativeMethods.GetSystemMetrics(SM.CYSIZEFRAME));
  103. Size frameSizeInDips = DpiHelper.DeviceSizeToLogical(frameSize);
  104. int captionHeight = NativeMethods.GetSystemMetrics(SM.CYCAPTION);
  105. double captionHeightInDips = DpiHelper.DevicePixelsToLogical(new Point(0, captionHeight)).Y;
  106. WindowNonClientFrameThickness = new Thickness(frameSizeInDips.Width, frameSizeInDips.Height + captionHeightInDips, frameSizeInDips.Width, frameSizeInDips.Height);
  107. }
  108. private void _UpdateWindowNonClientFrameThickness(IntPtr wParam, IntPtr lParam)
  109. {
  110. _InitializeWindowNonClientFrameThickness();
  111. }
  112. private void _InitializeSmallIconSize()
  113. {
  114. SmallIconSize = new Size(
  115. NativeMethods.GetSystemMetrics(SM.CXSMICON),
  116. NativeMethods.GetSystemMetrics(SM.CYSMICON));
  117. }
  118. private void _UpdateSmallIconSize(IntPtr wParam, IntPtr lParam)
  119. {
  120. _InitializeSmallIconSize();
  121. }
  122. private void _LegacyInitializeCaptionButtonLocation()
  123. {
  124. // This calculation isn't quite right, but it's pretty close.
  125. // I expect this is good enough for the scenarios where this is expected to be used.
  126. int captionX = NativeMethods.GetSystemMetrics(SM.CXSIZE);
  127. int captionY = NativeMethods.GetSystemMetrics(SM.CYSIZE);
  128. int frameX = NativeMethods.GetSystemMetrics(SM.CXSIZEFRAME) + NativeMethods.GetSystemMetrics(SM.CXEDGE);
  129. int frameY = NativeMethods.GetSystemMetrics(SM.CYSIZEFRAME) + NativeMethods.GetSystemMetrics(SM.CYEDGE);
  130. Rect captionRect = new Rect(0, 0, captionX * 3, captionY);
  131. captionRect.Offset(-frameX - captionRect.Width, frameY);
  132. WindowCaptionButtonsLocation = captionRect;
  133. }
  134. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
  135. private void _InitializeCaptionButtonLocation()
  136. {
  137. // There is a completely different way to do this on XP.
  138. if (!Utility.IsOSVistaOrNewer || !NativeMethods.IsThemeActive())
  139. {
  140. _LegacyInitializeCaptionButtonLocation();
  141. return;
  142. }
  143. var tbix = new TITLEBARINFOEX { cbSize = Marshal.SizeOf(typeof(TITLEBARINFOEX)) };
  144. IntPtr lParam = Marshal.AllocHGlobal(tbix.cbSize);
  145. try
  146. {
  147. Marshal.StructureToPtr(tbix, lParam, false);
  148. // This might flash a window in the taskbar while being calculated.
  149. // WM_GETTITLEBARINFOEX doesn't work correctly unless the window is visible while processing.
  150. NativeMethods.ShowWindow(_messageHwnd.Handle, SW.SHOW);
  151. NativeMethods.SendMessage(_messageHwnd.Handle, WM.GETTITLEBARINFOEX, IntPtr.Zero, lParam);
  152. tbix = (TITLEBARINFOEX)Marshal.PtrToStructure(lParam, typeof(TITLEBARINFOEX));
  153. }
  154. finally
  155. {
  156. NativeMethods.ShowWindow(_messageHwnd.Handle, SW.HIDE);
  157. Utility.SafeFreeHGlobal(ref lParam);
  158. }
  159. // TITLEBARINFOEX has information relative to the screen. We need to convert the containing rect
  160. // to instead be relative to the top-right corner of the window.
  161. RECT rcAllCaptionButtons = RECT.Union(tbix.rgrect_CloseButton, tbix.rgrect_MinimizeButton);
  162. // For all known themes, the RECT for the maximize box shouldn't add anything to the union of the minimize and close boxes.
  163. Assert.AreEqual(rcAllCaptionButtons, RECT.Union(rcAllCaptionButtons, tbix.rgrect_MaximizeButton));
  164. RECT rcWindow = NativeMethods.GetWindowRect(_messageHwnd.Handle);
  165. // Reorient the Top/Right to be relative to the top right edge of the Window.
  166. var deviceCaptionLocation = new Rect(
  167. rcAllCaptionButtons.Left - rcWindow.Width - rcWindow.Left,
  168. rcAllCaptionButtons.Top - rcWindow.Top,
  169. rcAllCaptionButtons.Width,
  170. rcAllCaptionButtons.Height);
  171. Rect logicalCaptionLocation = DpiHelper.DeviceRectToLogical(deviceCaptionLocation);
  172. WindowCaptionButtonsLocation = logicalCaptionLocation;
  173. }
  174. private void _UpdateCaptionButtonLocation(IntPtr wParam, IntPtr lParam)
  175. {
  176. _InitializeCaptionButtonLocation();
  177. }
  178. private void _InitializeHighContrast()
  179. {
  180. HIGHCONTRAST hc = NativeMethods.SystemParameterInfo_GetHIGHCONTRAST();
  181. HighContrast = (hc.dwFlags & HCF.HIGHCONTRASTON) != 0;
  182. }
  183. private void _UpdateHighContrast(IntPtr wParam, IntPtr lParam)
  184. {
  185. _InitializeHighContrast();
  186. }
  187. private void _InitializeThemeInfo()
  188. {
  189. if (!NativeMethods.IsThemeActive())
  190. {
  191. UxThemeName = "Classic";
  192. UxThemeColor = "";
  193. return;
  194. }
  195. string name;
  196. string color;
  197. string size;
  198. NativeMethods.GetCurrentThemeName(out name, out color, out size);
  199. // Consider whether this is the most useful way to expose this...
  200. UxThemeName = System.IO.Path.GetFileNameWithoutExtension(name);
  201. UxThemeColor = color;
  202. }
  203. private void _UpdateThemeInfo(IntPtr wParam, IntPtr lParam)
  204. {
  205. _InitializeThemeInfo();
  206. }
  207. private void _InitializeWindowCornerRadius()
  208. {
  209. // The radius of window corners isn't exposed as a true system parameter.
  210. // It instead is a logical size that we're approximating based on the current theme.
  211. // There aren't any known variations based on theme color.
  212. Assert.IsNeitherNullNorEmpty(UxThemeName);
  213. // These radii are approximate. The way WPF does rounding is different than how
  214. // rounded-rectangle HRGNs are created, which is also different than the actual
  215. // round corners on themed Windows. For now we're not exposing anything to
  216. // mitigate the differences.
  217. var cornerRadius = default(CornerRadius);
  218. // This list is known to be incomplete and very much not future-proof.
  219. // On XP there are at least a couple of shipped themes that this won't catch,
  220. // "Zune" and "Royale", but WPF doesn't know about these either.
  221. // If a new theme was to replace Aero, then this will fall back on "classic" behaviors.
  222. // This isn't ideal, but it's not the end of the world. WPF will generally have problems anyways.
  223. switch (UxThemeName.ToUpperInvariant())
  224. {
  225. case "LUNA":
  226. cornerRadius = new CornerRadius(6, 6, 0, 0);
  227. break;
  228. case "AERO":
  229. // Aero has two cases. One with glass and one without...
  230. if (NativeMethods.DwmIsCompositionEnabled())
  231. {
  232. cornerRadius = new CornerRadius(8);
  233. }
  234. else
  235. {
  236. cornerRadius = new CornerRadius(6, 6, 0, 0);
  237. }
  238. break;
  239. case "CLASSIC":
  240. case "ZUNE":
  241. case "ROYALE":
  242. default:
  243. cornerRadius = new CornerRadius(0);
  244. break;
  245. }
  246. WindowCornerRadius = cornerRadius;
  247. }
  248. private void _UpdateWindowCornerRadius(IntPtr wParam, IntPtr lParam)
  249. {
  250. // Neither the wParam or lParam are used in this case.
  251. _InitializeWindowCornerRadius();
  252. }
  253. #endregion
  254. /// <summary>
  255. /// Private constructor. The public way to access this class is through the static Current property.
  256. /// </summary>
  257. private SystemParameters2()
  258. {
  259. // This window gets used for calculations about standard caption button locations
  260. // so it has WS_OVERLAPPEDWINDOW as a style to give it normal caption buttons.
  261. // This window may be shown during calculations of caption bar information, so create it at a location that's likely offscreen.
  262. _messageHwnd = new MessageWindow((CS)0, WS.OVERLAPPEDWINDOW | WS.DISABLED, (WS_EX)0, new Rect(-16000, -16000, 100, 100), "", _WndProc);
  263. _messageHwnd.Dispatcher.ShutdownStarted += (sender, e) => Utility.SafeDispose(ref _messageHwnd);
  264. // Fixup the default values of the DPs.
  265. _InitializeIsGlassEnabled();
  266. _InitializeGlassColor();
  267. _InitializeCaptionHeight();
  268. _InitializeWindowNonClientFrameThickness();
  269. _InitializeWindowResizeBorderThickness();
  270. _InitializeCaptionButtonLocation();
  271. _InitializeSmallIconSize();
  272. _InitializeHighContrast();
  273. _InitializeThemeInfo();
  274. // WindowCornerRadius isn't exposed by true system parameters, so it requires the theme to be initialized first.
  275. _InitializeWindowCornerRadius();
  276. _UpdateTable = new Dictionary<WM, List<_SystemMetricUpdate>>
  277. {
  278. { WM.THEMECHANGED,
  279. new List<_SystemMetricUpdate>
  280. {
  281. _UpdateThemeInfo,
  282. _UpdateHighContrast,
  283. _UpdateWindowCornerRadius,
  284. _UpdateCaptionButtonLocation, } },
  285. { WM.SETTINGCHANGE,
  286. new List<_SystemMetricUpdate>
  287. {
  288. _UpdateCaptionHeight,
  289. _UpdateWindowResizeBorderThickness,
  290. _UpdateSmallIconSize,
  291. _UpdateHighContrast,
  292. _UpdateWindowNonClientFrameThickness,
  293. _UpdateCaptionButtonLocation, } },
  294. { WM.DWMNCRENDERINGCHANGED, new List<_SystemMetricUpdate> { _UpdateIsGlassEnabled } },
  295. { WM.DWMCOMPOSITIONCHANGED, new List<_SystemMetricUpdate> { _UpdateIsGlassEnabled } },
  296. { WM.DWMCOLORIZATIONCOLORCHANGED, new List<_SystemMetricUpdate> { _UpdateGlassColor } },
  297. };
  298. }
  299. public static SystemParameters2 Current
  300. {
  301. get
  302. {
  303. if (_threadLocalSingleton == null)
  304. {
  305. _threadLocalSingleton = new SystemParameters2();
  306. }
  307. return _threadLocalSingleton;
  308. }
  309. }
  310. private IntPtr _WndProc(IntPtr hwnd, WM msg, IntPtr wParam, IntPtr lParam)
  311. {
  312. // Don't do this if called within the SystemParameters2 constructor
  313. if (_UpdateTable != null)
  314. {
  315. List<_SystemMetricUpdate> handlers;
  316. if (_UpdateTable.TryGetValue(msg, out handlers))
  317. {
  318. Assert.IsNotNull(handlers);
  319. foreach (var handler in handlers)
  320. {
  321. handler(wParam, lParam);
  322. }
  323. }
  324. }
  325. return NativeMethods.DefWindowProc(hwnd, msg, wParam, lParam);
  326. }
  327. public bool IsGlassEnabled
  328. {
  329. get
  330. {
  331. // return _isGlassEnabled;
  332. // It turns out there may be some lag between someone asking this
  333. // and the window getting updated. It's not too expensive, just always do the check.
  334. return NativeMethods.DwmIsCompositionEnabled();
  335. }
  336. private set
  337. {
  338. if (value != _isGlassEnabled)
  339. {
  340. _isGlassEnabled = value;
  341. _NotifyPropertyChanged("IsGlassEnabled");
  342. }
  343. }
  344. }
  345. public Color WindowGlassColor
  346. {
  347. get { return _glassColor; }
  348. private set
  349. {
  350. if (value != _glassColor)
  351. {
  352. _glassColor = value;
  353. _NotifyPropertyChanged("WindowGlassColor");
  354. }
  355. }
  356. }
  357. public SolidColorBrush WindowGlassBrush
  358. {
  359. get { return _glassColorBrush; }
  360. private set
  361. {
  362. Assert.IsNotNull(value);
  363. Assert.IsTrue(value.IsFrozen);
  364. if (_glassColorBrush == null || value.Color != _glassColorBrush.Color)
  365. {
  366. _glassColorBrush = value;
  367. _NotifyPropertyChanged("WindowGlassBrush");
  368. }
  369. }
  370. }
  371. public Thickness WindowResizeBorderThickness
  372. {
  373. get { return _windowResizeBorderThickness; }
  374. private set
  375. {
  376. if (value != _windowResizeBorderThickness)
  377. {
  378. _windowResizeBorderThickness = value;
  379. _NotifyPropertyChanged("WindowResizeBorderThickness");
  380. }
  381. }
  382. }
  383. public Thickness WindowNonClientFrameThickness
  384. {
  385. get { return _windowNonClientFrameThickness; }
  386. private set
  387. {
  388. if (value != _windowNonClientFrameThickness)
  389. {
  390. _windowNonClientFrameThickness = value;
  391. _NotifyPropertyChanged("WindowNonClientFrameThickness");
  392. }
  393. }
  394. }
  395. public double WindowCaptionHeight
  396. {
  397. get { return _captionHeight; }
  398. private set
  399. {
  400. if (value != _captionHeight)
  401. {
  402. _captionHeight = value;
  403. _NotifyPropertyChanged("WindowCaptionHeight");
  404. }
  405. }
  406. }
  407. public Size SmallIconSize
  408. {
  409. get { return new Size(_smallIconSize.Width, _smallIconSize.Height); }
  410. private set
  411. {
  412. if (value != _smallIconSize)
  413. {
  414. _smallIconSize = value;
  415. _NotifyPropertyChanged("SmallIconSize");
  416. }
  417. }
  418. }
  419. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ux")]
  420. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ux")]
  421. public string UxThemeName
  422. {
  423. get { return _uxThemeName; }
  424. private set
  425. {
  426. if (value != _uxThemeName)
  427. {
  428. _uxThemeName = value;
  429. _NotifyPropertyChanged("UxThemeName");
  430. }
  431. }
  432. }
  433. [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ux")]
  434. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ux")]
  435. public string UxThemeColor
  436. {
  437. get { return _uxThemeColor; }
  438. private set
  439. {
  440. if (value != _uxThemeColor)
  441. {
  442. _uxThemeColor = value;
  443. _NotifyPropertyChanged("UxThemeColor");
  444. }
  445. }
  446. }
  447. public bool HighContrast
  448. {
  449. get { return _isHighContrast; }
  450. private set
  451. {
  452. if (value != _isHighContrast)
  453. {
  454. _isHighContrast = value;
  455. _NotifyPropertyChanged("HighContrast");
  456. }
  457. }
  458. }
  459. public CornerRadius WindowCornerRadius
  460. {
  461. get { return _windowCornerRadius; }
  462. private set
  463. {
  464. if (value != _windowCornerRadius)
  465. {
  466. _windowCornerRadius = value;
  467. _NotifyPropertyChanged("WindowCornerRadius");
  468. }
  469. }
  470. }
  471. public Rect WindowCaptionButtonsLocation
  472. {
  473. get { return _captionButtonLocation; }
  474. private set
  475. {
  476. if (value != _captionButtonLocation)
  477. {
  478. _captionButtonLocation = value;
  479. _NotifyPropertyChanged("WindowCaptionButtonsLocation");
  480. }
  481. }
  482. }
  483. #region INotifyPropertyChanged Members
  484. private void _NotifyPropertyChanged(string propertyName)
  485. {
  486. Assert.IsNeitherNullNorEmpty(propertyName);
  487. var handler = PropertyChanged;
  488. if (handler != null)
  489. {
  490. handler(this, new PropertyChangedEventArgs(propertyName));
  491. }
  492. }
  493. public event PropertyChangedEventHandler PropertyChanged;
  494. #endregion
  495. }
  496. }