Possible to cast active Microsoft Word window to WPF Window?

痴心易碎 提交于 2019-12-11 03:24:35

问题


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;


回答1:


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:


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;


来源:https://stackoverflow.com/questions/11861406/possible-to-cast-active-microsoft-word-window-to-wpf-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!