在子对话框窗口上查找windowwex
本文关键字:查找 windowwex 窗口 对话框 | 更新日期: 2023-09-27 18:14:54
我试图得到一个子对话框窗口的处理。我试过使用findwindowwex,但它不起作用。相反,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
从我的理解,findwindowwex应该工作,它是一个子窗口。
我正在运行windows xp,并且还尝试使用findwindowwex (vhandle, IntPtr。零,"#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);
我找到了一个解决方案。findwindowwex不起作用的原因是因为它只作用于具有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;
}