1

How can I tell if an hWnd belongs to one of my child controls?

I want to do something like:

if(this.Controls.Find(hWnd) != null) return false;
John Weldon
  • 39,849
  • 11
  • 94
  • 127

2 Answers2

3

There's a Win32 function for this: IsChild

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
2

Sounds like a great chance to use recursion. Add this function to your parent class:

  private bool IsChild(System.Windows.Forms.Control control, System.IntPtr hWnd)
  {
     if(control.Handle == hWnd)
        return(true);

     foreach (System.Windows.Forms.Control child in control.Controls)
     {
        if (IsChild(child, hWnd))
           return (true);
     }
     return (false);
  }

You can then use this function to search this parent class for any child controls with the specified hWnd:

this.IsChild(this, hWnd);
Andrew Garrison
  • 6,977
  • 11
  • 50
  • 77
  • thanks! I was hoping there was a faster way than iterating over child controls (especially if the hWnd belongs to a child of a child :) ) – John Weldon May 07 '09 at 15:57