|
1 | 1 | using System; |
2 | 2 | using System.Runtime.InteropServices; |
| 3 | +using System.Windows; |
| 4 | +using System.Windows.Interop; |
3 | 5 |
|
4 | 6 | namespace Demo.Utilities |
5 | 7 | { |
@@ -27,8 +29,36 @@ public class Win32 |
27 | 29 | internal static extern IntPtr GetTopWindow(IntPtr hWnd); |
28 | 30 | [DllImport("User32")] |
29 | 31 | internal static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd); |
30 | | - |
| 32 | + [DllImport("user32.dll", SetLastError=true)] |
| 33 | + static extern bool GetWindowRect(IntPtr hwnd, out W32Rect lpRect); |
| 34 | + [DllImport("shcore.dll",SetLastError = true)] |
| 35 | + private static extern uint SetProcessDpiAwareness(int awareness); |
31 | 36 | #endregion |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Gets the window rect in device units. |
| 40 | + /// </summary> |
| 41 | + /// <param name="window">The window.</param> |
| 42 | + /// <returns>Rect.</returns> |
| 43 | + public static Rect GetWindowRect(Window window) { |
| 44 | + var hwnd = new WindowInteropHelper(window).Handle; |
| 45 | + GetWindowRect(hwnd, out var r); |
| 46 | + return new Rect(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top); |
| 47 | + } |
| 48 | + |
| 49 | + private const int PROCESS_PER_MONITOR_DPI_AWARE = 2; |
| 50 | + /// <summary> |
| 51 | + /// Sets the dpi awareness for the current process to: per monitor dpi aware. |
| 52 | + /// </summary> |
| 53 | + public static void SetProcessDpiAwarenessPerMonitor() |
| 54 | + { |
| 55 | + var result = SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); |
| 56 | + switch (result) { |
| 57 | + case 0: return; |
| 58 | + case 0x80070005: return; // The DPI awareness is already set, either by calling this API previously or through the application (.exe) manifest. |
| 59 | + default: Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); return; |
| 60 | + } |
| 61 | + } |
32 | 62 | } |
33 | 63 |
|
34 | 64 | [StructLayout(LayoutKind.Sequential)] |
|
0 commit comments