Exemplo n.º 1
0
        /// <summary>
        /// Get rectangle of a specified window.
        /// </summary>
        /// <param name="source">Source Window</param>
        internal static Rect GetWindowRect(Window source)
        {
            var handleWindow = new WindowInteropHelper(source).Handle;

            try
            {
                NativeMethod.RECT targetRect;

                // For Windows XP or older
                var result = NativeMethod.GetWindowRect(
                    handleWindow,
                    out targetRect);
                if (!result)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (OsVersion.IsVistaOrNewer)
                {
                    // For Windows Vista or newer
                    bool isEnabled = false;

                    var result1 = NativeMethod.DwmIsCompositionEnabled(
                        ref isEnabled);
                    if (result1 != 0)                     // 0 means S_OK.
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    if (isEnabled)
                    {
                        var result2 = NativeMethod.DwmGetWindowAttribute(
                            handleWindow,
                            NativeMethod.DWMWA_EXTENDED_FRAME_BOUNDS,
                            ref targetRect,
                            Marshal.SizeOf(typeof(NativeMethod.RECT)));
                        if (result2 != 0)                         // 0 means S_OK.
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                }

                return(targetRect.ToRect());
            }
            catch (Win32Exception ex)
            {
                throw new Exception(String.Format("Failed to get window rect (Code: {0}).", ex.ErrorCode), ex);
            }
        }