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

I have a situation where I need to find the parent window or WinForm in which the WPF control is located. I need to get a handle to the parent window or WinForm anyway.

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

+4
source share
2 answers

Just got it!

var presentationSource = (HwndSource)PresentationSource.FromVisual(child); var parentHandle = presentationSource.Handle; 
+3
source
 [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 can then loop through the System.Windows.Forms.Application.OpenForms collection to find the WinForm matching the return value of the GetParentWindowHandle method above.

Alex D.

+1
source

Source: https://habr.com/ru/post/1312994/


All Articles