0
votes

I have a number of WPF dialogs in my Word Add-In. For one of them (and only one, strangely), it is sometimes not focused when opened. I believe I need to set its parent.

I know there is a way to set the owner of a WPF window to a HWND, but is there any way to get a HWND in Word 2010? I found this HWND property but it is Word 2013 and later only. Is there any other way to get Word's HWND, other than using GetForegroundWindow() which does not guarantee the handle for the window I actually want (or any other similar kludge)?

1

1 Answers

0
votes

I found something helpful in Get specific window handle using Office interop. But all those answers are based on getting the handle for a window you're newly creating. I modified it somewhat to get an existing window, and stuffed it into a utility method.

doc is the current document.

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;
    }
}

Unfortunately it doesn't seem to be possible to account for multiple windows with the same document name (in different folders), because the number of processes is never greater than 1. But I think that's an acceptable limitation.