首页 文章

获取Word的窗口句柄以与WPF窗口一起使用

提问于
浏览
0

我的Word加载项中有许多WPF对话框 . 对于其中一个(并且只有一个,奇怪的是),它有时在打开时不会聚焦 . 我相信我需要设置它的父母 .

我知道有a way to set the owner of a WPF window to a HWND,但有没有办法在Word 2010中获得HWND?我找到this HWND property但它只是Word 2013及更高版本 . 有没有其他方法来获得Word的HWND,除了使用GetForegroundWindow(),它不保证我实际想要的窗口(或任何其他类似的kludge)的句柄?

1 回答

  • 0

    我在Get specific window handle using Office interop找到了一些有用的东西 . 但所有这些答案都是基于获取新创建的窗口的句柄 . 我稍微修改它以获得一个现有的窗口,并将其填充到实用程序方法中 .

    doc 是当前文件 .

    using System.Windows.Interop;
    using System.Diagnostics;
    
    public void SetOwner(System.Windows.Window pd)
    {
        var wordProcs = Process.GetProcessesByName("winword").ToList();
        // in read-only mode, this would be e.g. "1.docx [Read-Only] - Microsoft Word"
        var procs = wordProcs.Where(x =>
              x.MainWindowTitle.StartsWith(Path.GetFileName(doc.FullName))
              &&
              x.MainWindowTitle.EndsWith("- Microsoft Word"));
        if (procs.Count() >= 1)
        {
            // would prefer Word 2013's Window.HWND property for this
            var handle = procs.First().MainWindowHandle;
            WindowInteropHelper wih = new WindowInteropHelper(pd);
            wih.Owner = handle;
        }
    }
    

    不幸的是,似乎没有可能考虑具有相同文档名称(在不同文件夹中)的多个窗口,因为进程数量永远不会大于1.但我认为这是可接受的限制 .

相关问题