3
votes

I've created a Microsoft Word 2010 vsto add-in which displays a number of custom Wpf Window dialogs when users click on ribbon buttons.

The issue I'm having is that the custom dialog dissapears behind the Word instance if you click the Word icon in the task bar.

After some Googling it appears that this can be fixed by setting the Owner property of my window, but I'm struggling to get the Window instance of the Word application.

I've attached the relevant code below, any suggestions?

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

2

2 Answers

2
votes

The exception clearly states that the answer to your question is No.

If Microsoft.Office.Interop.Word provides any means to get the window handle (HWND) of Word's main window (or if you get that handle by some Win32 call), you might try to set your window's owner by the WindowInteropHelper.Owner property.

2
votes

Used Clemens' suggestion to go with the WindowInteropHelper route, below is the complete code to get this working:

1) Define this pointer anywhere inside your class:

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

2) Add the following code to the window declaration code:

        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;