tags:

views:

1121

answers:

4

using Microsoft.Office.Interop.Word;

ApplicationClass _application = new ApplicationClass();

Can I get the PID from the Winword.exe process that was lunched by the _application?

I need the PID because with corrupted files, I just cant quit the ApplicationClass, even using this code:

_application.Quit(ref saveFile, ref missing, ref missing);          
System.Runtime.InteropServices.Marshal.ReleaseComObject(_application);
GC.Collect();
GC.WaitForPendingFinalizers();

I cant search for the winword.exe process and kill it, because I will have several and I don't know which one to kill. If I can get a PID for each ApplicationClass, I could just kill the correct winword.exe process that is giving me troubles to quit.

Thanks.

A: 

No, unfortunately there is no way to associate an instance of ApplicationClass with a running process of word.

Why do you need to kill the instance of word? Couldn't you just ask it to close all of it's documents and then simply stop using that instance? If you remove all references to the class eventually the GC will kick in and take down the COM server.

JaredPar
I just can't close the document because it is not opened yet. The document is corrupted so a window dialog appears waiting for a human intervention. However, I use the code in a service, and I open thousands of word documents, and a human intervention is impossible.I investigate a little more, and Excel ApplicationClass have a Hwnd. With:[DllImport("user32.dll")]static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);I can get the PID.But Word ApplicationClass doesn't have a Hwnd... What a shame...
Ricardo
A: 

The usual way to get it is to change Word's title to something unique and hop through the top-level window list until you find it (EnumWindows).

Joshua
A: 

http://www.codekeep.net/snippets/7835116d-b254-466e-ae66-666e4fa3ea5e.aspx

///Return Type: DWORD->unsigned int ///hWnd: HWND->HWND__* ///lpdwProcessId: LPDWORD->DWORD* [System.Runtime.InteropServices.DllImportAttribute( "user32.dll", EntryPoint = "GetWindowThreadProcessId" )] public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );

private int _ExcelPID = 0; Process _ExcelProcess;

private Application _ExcelApp = new ApplicationClass(); GetWindowThreadProcessId( new IntPtr(_ExcelApp.Hwnd), out _ExcelPID ); _ExcelProcess = System.Diagnostics.Process.GetProcessById( _ExcelPID );

...

_ExcelProcess.Kill();

A: 

hi
I met the problem which was the same to you.
There maybe something error in the word file,as a result, when you open the file with the method Word.ApplicationClass.Documents.Open(),there will be a dialog shown and the process will be hang.
Please use Word.ApplicationClass.Documents.OpenNoRepairDialog() instead, i found i fix the problem by it.

Edwin Tai