如何获得窗口标题?

时间:2012-11-05 22:58:23

标签: c# winapi

我想获得一个由spy ++(以红色突出显示)

给出的Window Caption

enter image description here

我有代码来获取窗口标题。它通过回调枚举所有窗口来执行此操作,该回调通过调用GetWindowText来检查窗口标题。如果caption = "window title | my application"的窗口是Open,那么我希望窗口标题包含在枚举中并被发现。

如果窗口计数不为1,则该函数释放任何窗口句柄并返回null。在返回null的情况下,这被认为是失败。在我运行此代码100次的一个测试用例中,我的失败计数为99.

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();
            }
        }

请注意,我已将"strTitle"的所有值都流式传输到文件中。然后在我的标题中对关键字执行了文本库搜索,但未成功。为什么枚举在某些情况下找不到我正在寻找的窗口,但在其他情况下呢?

1 个答案:

答案 0 :(得分:2)

你是如何运行100次的?...在​​紧密的循环中,重新启动应用程序等?

根据您的代码,如果您在循环中运行它而不清除集合,则由于错误条件if (collection.Count != 1),在找到的第一个条目之后,您将在每个找到的条目上出错。

然后在每个EnumDesktopWindows调用中,您只需添加到集合中,然后返回调用者。该集合永远不会被清除或重置,因此在添加第二项后,失败条件为真。

相关问题