ScreenUtils.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Windows;
  5. using System.Windows.Forms;
  6. using System.Windows.Interop;
  7. using Point = System.Windows.Point;
  8. namespace InABox.DynamicGrid
  9. {
  10. public class WpfScreen
  11. {
  12. private readonly Screen screen;
  13. internal WpfScreen(Screen screen)
  14. {
  15. this.screen = screen;
  16. }
  17. public static WpfScreen Primary => new(Screen.PrimaryScreen);
  18. public Rect DeviceBounds => GetRect(screen.Bounds);
  19. public Rect WorkingArea => GetRect(screen.WorkingArea);
  20. public bool IsPrimary => screen.Primary;
  21. public string DeviceName => screen.DeviceName;
  22. public static IEnumerable<WpfScreen> AllScreens()
  23. {
  24. foreach (var screen in Screen.AllScreens) yield return new WpfScreen(screen);
  25. }
  26. public static WpfScreen GetScreenFrom(Window window)
  27. {
  28. var windowInteropHelper = new WindowInteropHelper(window);
  29. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  30. var wpfScreen = new WpfScreen(screen);
  31. return wpfScreen;
  32. }
  33. public static WpfScreen GetScreenFrom(Point point)
  34. {
  35. var x = (int)Math.Round(point.X);
  36. var y = (int)Math.Round(point.Y);
  37. // are x,y device-independent-pixels ??
  38. var drawingPoint = new System.Drawing.Point(x, y);
  39. var screen = Screen.FromPoint(drawingPoint);
  40. var wpfScreen = new WpfScreen(screen);
  41. return wpfScreen;
  42. }
  43. private Rect GetRect(Rectangle value)
  44. {
  45. // should x, y, width, height be device-independent-pixels ??
  46. return new Rect
  47. {
  48. X = value.X,
  49. Y = value.Y,
  50. Width = value.Width,
  51. Height = value.Height
  52. };
  53. }
  54. public static void CenterWindowOnScreen(Window window)
  55. {
  56. var screen = GetScreenFrom(window);
  57. var screenWidth = screen.WorkingArea.Width;
  58. var screenHeight = screen.WorkingArea.Height;
  59. var windowWidth = window.Width;
  60. var windowHeight = window.Height;
  61. window.Left = screenWidth / 2 - windowWidth / 2;
  62. window.Top = screenHeight / 2 - windowHeight / 2;
  63. }
  64. }
  65. }