DpiHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Windows;
  4. using System.Windows.Media;
  5. namespace Standard;
  6. internal static class DpiHelper
  7. {
  8. [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
  9. static DpiHelper()
  10. {
  11. using (SafeDC desktop = SafeDC.GetDesktop())
  12. {
  13. int deviceCaps = NativeMethods.GetDeviceCaps(desktop, DeviceCap.LOGPIXELSX);
  14. int deviceCaps2 = NativeMethods.GetDeviceCaps(desktop, DeviceCap.LOGPIXELSY);
  15. DpiHelper._transformToDip = Matrix.Identity;
  16. DpiHelper._transformToDip.Scale(96.0 / (double) deviceCaps, 96.0 / (double) deviceCaps2);
  17. DpiHelper._transformToDevice = Matrix.Identity;
  18. DpiHelper._transformToDevice.Scale((double) deviceCaps / 96.0, (double) deviceCaps2 / 96.0);
  19. }
  20. }
  21. public static Point LogicalPixelsToDevice(Point logicalPoint)
  22. {
  23. return DpiHelper._transformToDevice.Transform(logicalPoint);
  24. }
  25. public static Point DevicePixelsToLogical(Point devicePoint)
  26. {
  27. return DpiHelper._transformToDip.Transform(devicePoint);
  28. }
  29. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  30. public static Rect LogicalRectToDevice(Rect logicalRectangle)
  31. {
  32. Point point = DpiHelper.LogicalPixelsToDevice(new Point(logicalRectangle.Left, logicalRectangle.Top));
  33. Point point2 = DpiHelper.LogicalPixelsToDevice(new Point(logicalRectangle.Right, logicalRectangle.Bottom));
  34. return new Rect(point, point2);
  35. }
  36. public static Rect DeviceRectToLogical(Rect deviceRectangle)
  37. {
  38. Point point = DpiHelper.DevicePixelsToLogical(new Point(deviceRectangle.Left, deviceRectangle.Top));
  39. Point point2 = DpiHelper.DevicePixelsToLogical(new Point(deviceRectangle.Right, deviceRectangle.Bottom));
  40. return new Rect(point, point2);
  41. }
  42. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
  43. public static Size LogicalSizeToDevice(Size logicalSize)
  44. {
  45. Point point = DpiHelper.LogicalPixelsToDevice(new Point(logicalSize.Width, logicalSize.Height));
  46. return new Size
  47. {
  48. Width = point.X,
  49. Height = point.Y
  50. };
  51. }
  52. public static Size DeviceSizeToLogical(Size deviceSize)
  53. {
  54. Point point = DpiHelper.DevicePixelsToLogical(new Point(deviceSize.Width, deviceSize.Height));
  55. return new Size(point.X, point.Y);
  56. }
  57. private static Matrix _transformToDevice;
  58. private static Matrix _transformToDip;
  59. }