Example #1
0
        /// <summary>
        ///     Gets the title of a window.
        /// </summary>
        /// <param name="hWnd"> The window. </param>
        /// <returns>
        ///     The title of the window or null if the title cannot be retrieved or <paramref name="hWnd" /> is
        ///     <see cref="IntPtr.Zero" />.
        /// </returns>
        /// <remarks>
        ///     <para>
        ///         Retrieving a window title can fail in cases the window is blocked and does not react to window messages within
        ///         one second.
        ///     </para>
        /// </remarks>
        public static string GetWindowTitle(IntPtr hWnd)
        {
            if (hWnd == IntPtr.Zero)
            {
                return(null);
            }

            int length = -1;

            WindowsWindow.SendMessageTimeout1(hWnd, WindowsWindow.WmGettextlength, IntPtr.Zero, IntPtr.Zero,
                                              WindowsWindow.SmtoAbortifhung | WindowsWindow.SmtoNormal, 1000,
                                              ref length);

            if (length == -1)
            {
                return(null);
            }

            if (length == 0)
            {
                return(string.Empty);
            }

            if (length > 10240)
            {
                return(null);
            }

            StringBuilder sb = new StringBuilder(length + 1);

            IntPtr temp = new IntPtr();

            WindowsWindow.SendMessageTimeout2(hWnd, WindowsWindow.WmGettext, new IntPtr(sb.Capacity), sb,
                                              WindowsWindow.SmtoAbortifhung | WindowsWindow.SmtoNormal, 1000, ref temp);

            if (temp.ToInt64() == -1)
            {
                return(null);
            }

            if (temp.ToInt64() == 0)
            {
                return(string.Empty);
            }

            string title = sb.ToString();

            return(title);
        }