locked
How to get ElementHost given a WPF control RRS feed

  • Question

  • At certain point of my code, I can get a WPF control of type System.Windows.Controls.Control. How can I find out whether the control is hosted in a ElementHost. If the control is hosted, how to find out the ElementHost that is hosting it?

     

    I tried something like control.Parent and trying to cast it to ElementHost, it does not even compile.

    Tuesday, July 3, 2007 12:01 AM

Answers

  • Thanks, Chango. Your solution works. You can skip step 3 though. I wrote some sample code like this:

     

    HwndSource wpfHandle = PresentationSource.FromVisual( mWpfCtrl ) as HwndSource;

    //the WPF control is hosted if the wpfHandle is not null

    if (wpfHandle != null)

    {

        ElementHost host = System.Windows.Forms.Control.FromChildHandle( wpfHandle.Handle ) as ElementHost;

    }

    Friday, July 6, 2007 6:27 AM

All replies

  • Something along these lines should work:

    1. PresentationSource.FromVisual(wpfControl) -> ElementHost's internal HwndSource

    2. HwndSource.Handle -> native window's handle (hwndWpf)

    3. Win32.GetParent(hwndWpf) -> ElementHost's window (hElementHost)

    4. System.Windows.Forms.Control.FromHandle(hElementHost) -> ElementHost

    Wednesday, July 4, 2007 5:39 AM
  • Thanks, Chango. Your solution works. You can skip step 3 though. I wrote some sample code like this:

     

    HwndSource wpfHandle = PresentationSource.FromVisual( mWpfCtrl ) as HwndSource;

    //the WPF control is hosted if the wpfHandle is not null

    if (wpfHandle != null)

    {

        ElementHost host = System.Windows.Forms.Control.FromChildHandle( wpfHandle.Handle ) as ElementHost;

    }

    Friday, July 6, 2007 6:27 AM