0

I have two files demo1.docx,demo2.docx.When I will open these two files then it created two instances into Task Manager in Application Section and created one process WinWord.exe into process Section.When I kill demo1.docx instance it automatically kill another instance but I want to kill only that instance demo1.docx. Currently I am using this code for kill the instance

string instanceName="demo1.docx";

Process[] runingProcess = Process.GetProcesses();
for (int i = 0; i < runingProcess.Length; i++)
    if (runingProcess[i].MainWindowTitle.Contains(instanceName))
        runingProcess[i].Kill();
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user3817749
  • 99
  • 1
  • 11

2 Answers2

4

We have to close them, not kill them. To take control of instance already running, you can use this code:

if (Process.GetProcessesByName("winword").Count() > 0)
{
    Word.Application wordInstance = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");

    foreach (Word.Document doc in wordInstance.Documents)
    {
        if (doc.Name == "demo1.docx")
        {
            doc.Close();
            break;
        }
     }
}
JeremyK
  • 1,075
  • 1
  • 22
  • 45
dovid
  • 6,354
  • 3
  • 33
  • 73
0

Since all documents are opened in the same process, killing it will automatically close all of them. Maybe you can use Word Automation to close a specific document.

Here there is a working solution : how to close a running instance of Word document? (C#)

Community
  • 1
  • 1
AFract
  • 8,868
  • 6
  • 48
  • 70