2015-06-29 38 views
0

如果我直接創建HwndSource,那麼我是否也創建了一個WPF Window,我現在可以從代碼訪問?如果是這樣,我該如何訪問它?如何從「我直接創建的HwndSource中獲取WPF窗口?

或者我現在需要以某種方式將WPF Window「添加」到HwndSource?如果是這樣,我該怎麼做?

我已經徹底研究了HwndSource文檔,這部分內容沒有很好地解釋。我知道我可以從現有的WPF窗口獲得HwndSource,但這對我沒有幫助。我需要攔截Window的創建,所以我可以強制它爲WS_CHILD風格並直接設置它的父項;並且文檔說你必須直接創建HwndSource,如果你想強制它的父類。

編輯:我一直在研究每個問題,我可以找到HwndSource在它;它看起來像你一樣,通過將HwndSource對象的RootVisual屬性設置爲要顯示的WPF對象,將WPF對象「添加」到HwndSource對象;或者可能通過調用HwndSourceAddSource方法?接下來會檢查那些人。希望這對其他提問者有用。

+0

https://msdn.microsoft.com/en-us/library/ms588468(v=vs.110).aspx –

回答

1

正如我懷疑,解決方案是將您的WPF對象添加到HwndSource.RootVisual對象。在下面的例子中,NativeMethods是我的Win32 API的PInvoke類。使用SetLastError和GetLastError檢查Windows錯誤。

請注意,在這種情況下,您必須使用用戶控制或頁面等;您不能將HwndSource.RootVisual設置爲現有或「新」WPF窗口,因爲WPF Windows已經有一個Parent,並且它不會接受帶有Parent的對象。

private void ShowPreview(IntPtr hWnd) 
    { 
     if (NativeMethods.IsWindow(hWnd)) 
     { 
      // Get the rect of the desired parent. 
      int error = 0; 
      System.Drawing.Rectangle ParentRect = new System.Drawing.Rectangle(); 
      NativeMethods.SetLastErrorEx(0, 0); 
      bool fSuccess = NativeMethods.GetClientRect(hWnd, ref ParentRect); 
      error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); 

      // Create the HwndSource which will host our Preview user control 
      HwndSourceParameters parameters = new HwndSourceParameters(); 
      parameters.WindowStyle = NativeMethods.WindowStyles.WS_CHILD | NativeMethods.WindowStyles.WS_VISIBLE; 
      parameters.SetPosition(0, 0); 
      parameters.SetSize(ParentRect.Width, ParentRect.Height); 
      parameters.ParentWindow = hWnd; 
      HwndSource src = new HwndSource(parameters); 

      // Create the user control and attach it 
      PreviewControl Preview = new PreviewControl(); 
      src.RootVisual = Preview; 
      Preview.Visibility = Visibility.Visible; 
     } 
    }