【问题标题】:Get Word's window handle to use with WPF windows获取 Word 的窗口句柄以与 WPF 窗口一起使用
【发布时间】:2016-06-16 20:26:26
【问题描述】:

我的 Word 加载项中有许多 WPF 对话框。对于其中一个(奇怪的是只有一个),打开时有时不集中。我相信我需要设置它的父级。

我知道有a way to set the owner of a WPF window to a HWND,但是有没有办法在 Word 2010 中获得 HWND?我找到了this HWND property,但它只是 Word 2013 及更高版本。除了使用 GetForegroundWindow() 之外,还有其他方法可以获取 Word 的 HWND,它不能保证我真正想要的窗口的句柄(或任何其他类似的组合)?

【问题讨论】:

    标签: ms-word vsto word-2010


    【解决方案1】:

    我在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。但我认为这是一个可以接受的限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 2011-02-26
      • 1970-01-01
      • 2014-01-28
      • 2012-11-22
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      相关资源
      最近更新 更多