title: Attach DirectShow video window to WPF Control
body: <p>I'm using DirectShow.NET to create a web camera control for WPF. I've successfully created a graph and can get video from a camera to display on my screen. However, the video output is completely independent of the WPF control it's being created in. </p>
  
  <p>I am setting the owner of the video window by calling <code>videoWindow.put_owner(hWnd)</code>, where <code>hWnd</code> is the window handle to the current WPF window. I get that window handle using the <code>WindowInteropHelper</code>. </p>
  
  <p>Here is the main routine:</p>
  
  <pre><code>public void CaptureVideo()
          {
              int hr = 0;
              IBaseFilter sourceFilter = null;
  
              try
              {
                  hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
                  DsError.ThrowExceptionForHR(hr);
  
                  sourceFilter = FindCaptureDevice();
  
                  hr = this.graphBuilder.AddFilter(sourceFilter, "Video Capture");
                  DsError.ThrowExceptionForHR(hr);
  
                  hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, null, null);
                  DsError.ThrowExceptionForHR(hr);
  
                  Marshal.ReleaseComObject(sourceFilter);
  
                  SetupVideoWindow();
  
                  hr = this.mediaControl.Run();
                  DsError.ThrowExceptionForHR(hr);
              }
              catch
              {
                  Console.WriteLine("An unrecoverable DirectShow error has occurred.");
              }
          }
  </code></pre>
  
  <p>And the code for SetupVideoWindow():</p>
  
  <pre><code>public void SetupVideoWindow()
          {
              int hr = 0;
  
              Window window = Window.GetWindow(this);
              var wih = new WindowInteropHelper(window);
              IntPtr hWnd = wih.Handle;
  
              hr = this.videoWindow.put_Owner(hWnd);
              DsError.ThrowExceptionForHR(hr);
  
              hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipChildren);
              DsError.ThrowExceptionForHR(hr);
  
              this.videoWindow.SetWindowPosition(0, 0, (int)this.Width, (int)this.Height);
  
              hr = this.videoWindow.put_Visible(OABool.True);
              DsError.ThrowExceptionForHR(hr);
          }
  </code></pre>
  
  <p>Here is an image of what is happening:
  <a href="https://i.stack.imgur.com/fdVUI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fdVUI.png" alt="DirectShow.NET Video Window and WPF MainWindow Control"></a></p>