2012-08-08 98 views
2

我創建了一個Microsoft Word 2010 vsto加載項,當用戶單擊功能區按鈕時,它會顯示一些自定義的Wpf窗口對話框。可能將激活的Microsoft Word窗口強制轉換爲WPF窗口?

我遇到的問題是如果您單擊任務欄中的Word圖標,自定義對話框消失在Word實例後面。

經過一些谷歌搜索後,它似乎可以通過設置我的窗口的所有者屬性來解決,但我努力獲得Word應用程序的Window實例。

我附上了下面的相關代碼,有什麼建議嗎?

using WordNS = Microsoft.Office.Interop.Word; 

Window wrapperWindow = new Window(); 
wrapperWindow.ResizeMode = ResizeMode.NoResize; 
wrapperWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; 
wrapperWindow.ShowInTaskbar = false; 
wrapperWindow.Content = dialogViewModel.View; 
wrapperWindow.Title = dialogViewModel.Title; 
wrapperWindow.SizeToContent = SizeToContent.WidthAndHeight; 

WordNS.Application app = (WordNS.Application)Marshal.GetActiveObject("Word.Application"); 
wrapperWindow.Owner = (Window)app.ActiveWindow; 

Invalid cast exception when casting ActiveWindow to Window

回答

1

二手克萊門斯的建議,去與WindowInteropHelper路線,下面是完整的代碼得到這個工作:

1)在任何地方定義類裏面這個指針:

[DllImport("user32.dll")] 
private static extern IntPtr GetForegroundWindow(); 

2)添加下面的代碼到窗口聲明代碼:

 Window wrapperWindow = new Window(); 
     //Set all the relevant window properties 

     //Set the owner of the window to the Word application 
     IntPtr wordWindow = GetForegroundWindow(); 
     WindowInteropHelper wih = new WindowInteropHelper(wrapperWindow); 
     wih.Owner = wordWindow; 
+0

我相信我已經試過這個,雖然它的作品,活動窗口不一定是Word窗口。 – Chris 2016-06-16 20:20:55

1

異常明確指出,回答你的問題是

如果Microsoft.Office.Interop.Word提供任何手段來獲得Word的主窗口的窗口句柄(HWND)(或者,如果你通過一些Win32調用來獲得該句柄),則可以嘗試通過WindowInteropHelper.Owner屬性設置窗口的所有者。