Search code examples
c#wpfwinformswinforms-interop

How to check if WPF control is hosted within WinForms?


I have a WPF control which in some cases exists as a component of WPF application and in the other is hosted in Windows Forms. How can I detect the second case (a WPF control is embedded inside WinForms)?


Solution

  • Try this:

    HwndSource wpfHandle = PresentationSource.FromVisual(this) as HwndSource;
    if (wpfHandle != null)
    {
        ElementHost host = System.Windows.Forms.Control.FromChildHandle(wpfHandle.Handle) as ElementHost;
        if(host != null)
        {
            //hosted in ElementHost...
        }
    }