2

我正在尝试获取子对话框窗口的句柄。我试过使用 FindWindowEx,但没有用。相反,FindWindow 确实有效。

我用 Visual Studio 的选项窗口做了一个实验,代码如下:

IntPtr vsHandle = Process.GetProcessById(vsProcessId).MainWindowHandle; // consistent with spy++'s parent handle of options window

IntPtr optionsHandle = FindWindowEx(vsHandle, IntPtr.Zero, "#32770", "Options"); // returns 0

IntPtr optionsHandle2 = FindWindow("#32770", "Options"); // returns correct handle

据我了解, FindWindowEx 应该可以工作,它是一个子窗口。

我正在运行 windows xp,并且还尝试使用 FindWindowEx(vsHandle, IntPtr.Zero, "#32770", null)。没用。似乎获得它的唯一方法是使用 FindWindow 这还不够好,因为可以打开具有相同对话框的两个父实例。

这是声明:

[DllImport("user32.dll")]
Private static extern IntPtr FindWindow(string className, string windowTitle);
[DllImport("user32.dll")]
Private static extern IntPtr FindWindowEx(IntPtr parentHWnd, IntPtr childAfterHWnd,     string className, string windowTitle);

提前致谢。

4

1 回答 1

6

我找到了解决方案。FindWindowEx 不起作用的原因是它只适用于具有 WS_CHILD 样式的子窗口,而对话框窗口显然没有这种样式。这就是 EnumChildWindows 也不起作用的原因(我试过了)。

所以丑陋的解决方案是 EnumWindows 结合 GetParent 来比较句柄和文本。

        struct SearchData
        {
            public string WindowText;
            public IntPtr ParentHandle;
            public IntPtr ResultHandle;
        }

        delegate bool EnumWindowsCallback(IntPtr currentWindowHandle, ref SearchData searchData);

        [DllImport("user32.dll")] static extern bool EnumWindows(EnumWindowsCallback callback, ref SearchData searchData);

        [DllImport("user32.dll")] static extern IntPtr GetParent(IntPtr childHandle);

        [DllImport("user32.dll")] static extern void GetWindowText(IntPtr handle, StringBuilder resultWindowText, int maxTextCapacity);


        static bool Callback(IntPtr currentWindowHandle, ref SearchData searchData)
        {
            bool continueEnumeration = true;

            IntPtr currentWindowParentHandle = GetParent(currentWindowHandle);

            if (currentWindowParentHandle == searchData.ParentHandle)
            {
                var windowText = new StringBuilder(1024);
                GetWindowText(currentWindowHandle, windowText, windowText.Capacity);

                if (windowText.ToString() == searchData.WindowText)
                {
                    searchData.ResultHandle = currentWindowHandle;
                    continueEnumeration = false;
                }
            }

            return continueEnumeration;
        }


        IntPtr GetChildWindowHandle(string windowText, IntPtr parentHandle)
        {
            var searchData = new SearchData{ParentHandle=parentHandle, WindowText=windowText};

            EnumWindows(Callback, ref searchData);

            return searchData.ResultHandle;
        }
于 2013-06-05T08:16:06.783 回答