首页 文章

可以将活动的Microsoft Word窗口转换为WPF窗口吗?

提问于
浏览
2

我创建了一个Microsoft Word 2010 vsto加载项,当用户单击功能区按钮时,该加载项会显示许多自定义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

2 回答

  • 1

    使用Clemens建议使用 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;
    
  • 1

    例外明确指出您的问题的答案是否定的 .

    如果 Microsoft.Office.Interop.Word 提供了通过WindowInteropHelper.Owner属性获取Word 's main window (or if you get that handle by some Win32 call), you might try to set your window'所有者的窗口句柄(HWND)的任何方法 .

相关问题