How do I get a window caption?

Posted by P.Brian.Mackey on Stack Overflow See other posts from Stack Overflow or by P.Brian.Mackey
Published on 2012-11-05T22:58:23Z Indexed on 2012/11/05 22:59 UTC
Read the original article Hit count: 347

Filed under:
|

I would like to get a Window Caption as given by spy++ (highlighted in red)

enter image description here

I have code to do this (or so I thought)...but it seems to work pretty awful....in some cases 1% of the time...

public delegate bool EnumDelegate(IntPtr hWnd, int lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);

        [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam);

        static List<NativeWindow> collection = new List<NativeWindow>();

public static NativeWindow GetAppNativeMainWindow()
        {            
            GetNativeWindowHelper.EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
            {
                StringBuilder strbTitle = new StringBuilder(255);
                int nLength = GetNativeWindowHelper.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
                string strTitle = strbTitle.ToString();

                if (!string.IsNullOrEmpty(strTitle))
                {
                    if (strTitle.ToLower().StartsWith("window title | my application"))
                    {
                        NativeWindow window = new NativeWindow();
                        window.AssignHandle(hWnd);
                        collection.Add(window);
                        return false;//stop enumerating
                    }
                }
                return true;//continue enumerating
            };

            GetNativeWindowHelper.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero);
            if (collection.Count != 1)
            {
                //log error

                ReleaseWindow();
                return null;
            }                    
            else
                return collection[0];
        }

        public static void ReleaseWindow()
        {
            foreach (var item in collection)
            {
                item.ReleaseHandle();
            }
        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about winapi