简体   繁体   中英

Identify process id of word instance using System.Diagnostics.Process object

I have code which starts Word application instance as follows

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
app.Caption = "abcd_" + DateTime.Now.Ticks.ToString();

I now need to know process id of the word instance that was started. I cannot use FindWindow to get window handle and GetWindowThreadProcessId to get process id from handle as the code does not work on Windows server 2008.

I get all word processes by using Process.GetProcessesByName("WINWORD") . Is there any property of Process which can give me value that we set in app.Caption ? If not, is there any other property of Word.Application which I can set and later on read from Process array to identify correct instance of Word ?

You Could use the Process.MainWindowTitle property to judge if the process is by your code.

But there's some limitation:

  1. When you using new Microsoft.Office.Interop.Word.Application(), the word windows is not visible by default. When it's hidden, the Process.MainWindowTitle is empty. So you show set it visible before you get the Pid.

  2. After you open a document, the MainWindowTitle will change to the document's file name.

Here's my code:

    static void Main(string[] args)
    {
        string uniCaption = Guid.NewGuid().ToString();
        Word.Application oWordApp = new Word.Application();
        oWordApp.Caption = uniCaption;
        oWordApp.Visible = true;

        Process pWord = getWordProcess(uniCaption);

        //If you don't want to show the Word windows
        oWordApp.Visible = false;

        //Do other things like open document etc.
    }

    static Process getWordProcess(string pCaption)
    {
        Process[] pWords = Process.GetProcessesByName("WINWORD");
        foreach (Process pWord in pWords)
        {
            if (pWord.MainWindowTitle == pCaption)
            {
                return pWord;
            }
        }

        return null;
    }

What about that (untestet):

Updated

Word.Application wdapp;
try 
{     
    Process wordProcess = System.Diagnostics.Process.Start("Path to WINWORD.EXE");
    wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
} 
catch (COMException) 
{
     Type type = Type.GetTypeFromProgID("Word.Application");
     wdapp = System.Activator.CreateInstance(type);
 } 

The wdApp should be the started word. And you get the process id through wordProcess instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM