Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 599
Joe.Net Avatar asked Oct 08 '22 12:10

Joe.Net


1 Answers

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);
like image 183
Rich Wawrzonek Avatar answered Oct 13 '22 00:10

Rich Wawrzonek