Advertisement
uwekeim

Get window size no matter which platform (including Win 8)

May 10th, 2013
624
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. public static class WindowHelper
  2. {
  3.     // https://code.google.com/p/zscreen/source/browse/trunk/ZScreenLib/Global/GraphicsCore.cs?r=1349
  4.  
  5.     /// <summary>
  6.     /// Get real window size, no matter whether Win XP, Win Vista, 7 or 8.
  7.     /// </summary>
  8.     public static Rectangle GetWindowRectangle(IntPtr handle)
  9.     {
  10.         if (Environment.OSVersion.Version.Major < 6)
  11.         {
  12.             return GetWindowRect(handle);
  13.         }
  14.         else
  15.         {
  16.             Rectangle rectangle;
  17.             return DWMWA_EXTENDED_FRAME_BOUNDS(handle, out rectangle) ? rectangle : GetWindowRect(handle);
  18.         }
  19.     }
  20.  
  21.     [DllImport(@"dwmapi.dll")]
  22.     private static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute);
  23.  
  24.     private enum Dwmwindowattribute
  25.     {
  26.         DwmwaExtendedFrameBounds = 9
  27.     }
  28.  
  29.     [Serializable, StructLayout(LayoutKind.Sequential)]
  30.     private struct Rect
  31.     {
  32.         // ReSharper disable MemberCanBePrivate.Local
  33.         // ReSharper disable FieldCanBeMadeReadOnly.Local
  34.         public int Left;
  35.         public int Top;
  36.         public int Right;
  37.         public int Bottom;
  38.         // ReSharper restore FieldCanBeMadeReadOnly.Local
  39.         // ReSharper restore MemberCanBePrivate.Local
  40.  
  41.         public Rectangle ToRectangle()
  42.         {
  43.             return Rectangle.FromLTRB(Left, Top, Right, Bottom);
  44.         }
  45.     }
  46.  
  47.     private static bool DWMWA_EXTENDED_FRAME_BOUNDS(IntPtr handle, out Rectangle rectangle)
  48.     {
  49.         Rect rect;
  50.         var result = DwmGetWindowAttribute(handle, (int)Dwmwindowattribute.DwmwaExtendedFrameBounds,
  51.             out rect, Marshal.SizeOf(typeof(Rect)));
  52.         rectangle = rect.ToRectangle();
  53.         return result >= 0;
  54.     }
  55.  
  56.     [DllImport(@"user32.dll")]
  57.     [return: MarshalAs(UnmanagedType.Bool)]
  58.     private static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
  59.  
  60.     private static Rectangle GetWindowRect(IntPtr handle)
  61.     {
  62.         Rect rect;
  63.         GetWindowRect(handle, out rect);
  64.         return rect.ToRectangle();
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement