Trainee4Life
Trainee4Life

Reputation: 2273

How to find in code the parent Window or WinForm of a WPF control?

I have a situation where I need to find the parent Window or WinForm which is hosting the WPF control. I need to get the handle of either the parent Window or WinForm whatever the case may be.

The problem is when the WPF control is hosted in a WinForm using ElementHost. How can I find the Handle of the hosting WinForm from a WPF control.

Upvotes: 4

Views: 2337

Answers (2)

Alexander
Alexander

Reputation: 253

[DllImport("user32.dll")]
        public static extern int GetParent(int hwnd);

        public int GetParentWindowHandle(Visual child)
        {
            HwndSource presentationSource = (HwndSource)PresentationSource.FromVisual(child);

            int parentHandle = presentationSource.Handle.ToInt32();
            int handle = parentHandle;

            while (parentHandle != 0)
            {
                handle = parentHandle;
                parentHandle = ApplicationHelperInterop.GetParent(parentHandle);
            }

            return handle;
        }

You could then loop through System.Windows.Forms.Application.OpenForms collection to find a WinForm corresponding to the return value of GetParentWindowHandle method above.

Alex D.

Upvotes: 2

Trainee4Life
Trainee4Life

Reputation: 2273

Just figured it out!

var presentationSource = (HwndSource)PresentationSource.FromVisual(child);
var parentHandle = presentationSource.Handle;

Upvotes: 3

Related Questions