Search code examples
c#vbaoffice-interopms-word

How do I get the Hwnd / Process Id for a Word Application, and set as Foreground Window


I want to my Word Application to come to the Foreground when automation has completed.

The equivalent in Excel is straight forward - the Excel Application object has a .Hwnd property which you can use in conjunction with the Windows API :

SetForegroundWindow((IntPtr)excelApp.Hwnd);

However the Word application does not have a .Hwnd property.

I've tried using Activate() in this sequence:

wordDoc.Activate();
wordApp.Activate();

but this does not work.

I've had a look at finding the process using the application name, but there could be more than one copy of Word running.

Thanks

Joe


Solution

  • You may need to iterate the processArray beyond the first. With word 2010 only one WinWord shows in the task manager no matter how many instances are open.

    System.Diagnostics.Process[] processArray =
        System.Diagnostics.Process.GetProcessesByName("WinWord");
    System.Diagnostics.Process word = processArray[0];
    SetForegroundWindow(word.MainWindowHandle);