如何在控件中找到句柄?

时间:2015-05-09 15:12:52

标签: c# winforms winapi webbrowser-control findwindow

我的应用程序中的WebBrowser引发了一个DialogBox,我需要找到它。我试过这个:

FindWindowEx(webBrowserEx1.Handle, IntPtr.Zero, "#32770", "title here")

但确实会返回IntPtr.Zero

它确实可以正常工作:

FindWindow("#32770", "title here")

但我想仅在webBrowserEx1控件内搜索窗口,而不是像FindWindow()那样搜索全局搜索

更新:使用spy ++我可以看到DialogBox的第一个子窗口和所有者都不是WebBrowser的DialogBox(我想那是' s为什么它不起作用)但父窗口是我自己的应用程序(托管WebBrowser的地方)所以我更新了我的代码:

handle = FindWindowEx(this.Handle, IntPtr.Zero, "#32770", "title here");

但它也没有奏效。

1 个答案:

答案 0 :(得分:1)

可能是Dialog不是WebBrowser的直接孩子 - 也许你可以用Spy ++验证它。

就在昨天巧合,我偶然发现了一些我多年前用于递归搜索子窗口的c#代码。也许这会有所帮助:

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

/// <summary>
/// Uses FindWindowEx() to recursively search for a child window with the given class and/or title.
/// </summary>
public static IntPtr FindChildWindow( IntPtr hwndParent, string lpszClass, string lpszTitle )
{
 return FindChildWindow( hwndParent, IntPtr.Zero, lpszClass, lpszTitle );
}

/// <summary>
/// Uses FindWindowEx() to recursively search for a child window with the given class and/or title,
/// starting after a specified child window.
/// If lpszClass is null, it will match any class name. It's not case-sensitive.
/// If lpszTitle is null, it will match any window title.
/// </summary>
public static IntPtr FindChildWindow( IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszTitle )
{
 // Try to find a match.
 IntPtr hwnd = FindWindowEx( hwndParent, IntPtr.Zero, lpszClass, lpszTitle );
 if ( hwnd == IntPtr.Zero )
 {
  // Search inside the children.
  IntPtr hwndChild = FindWindowEx( hwndParent, IntPtr.Zero, null, null );
  while ( hwndChild != IntPtr.Zero && hwnd == IntPtr.Zero )
  {
   hwnd = FindChildWindow( hwndChild, IntPtr.Zero, lpszClass, lpszTitle );
   if ( hwnd == IntPtr.Zero )
   {
    // If we didn't find it yet, check the next child.
    hwndChild = FindWindowEx( hwndParent, hwndChild, null, null );
   }
  }
 }
 return hwnd;
}