how to close a running instance of Word document? (C#)

此生再无相见时 提交于 2019-11-27 22:29:08

This solution got from here solves.

Word.Application app = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
if (app == null)
    return true;

foreach (Word.Document d in app.Documents)
{
    if (d.FullName.ToLower() == osPath.ToLower())
    {
        object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
        object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;
        object routeDocument = false;
        d.Close(ref saveOption, ref originalFormat, ref routeDocument);
        return true;
    }
}
return true;

How about using something like:

Modified From: http://www.dreamincode.net/code/snippet1541.htm

public static bool KillProcess(string name)
{
    //here we're going to get a list of all running processes on
    //the computer
    foreach (Process clsProcess in Process.GetProcesses())
    {
        if (Process.GetCurrentProcess().Id == clsProcess.Id)
            continue;
        //now we're going to see if any of the running processes
        //match the currently running processes. Be sure to not
        //add the .exe to the name you provide, i.e: NOTEPAD,
        //not NOTEPAD.EXE or false is always returned even if
        //notepad is running.
        //Remember, if you have the process running more than once, 
        //say IE open 4 times the loop thr way it is now will close all 4,
        //if you want it to just close the first one it finds
        //then add a return; after the Kill
        if (clsProcess.ProcessName.Contains(name))
        {
            clsProcess.Kill();
            return true;
        }
    }
    //otherwise we return a false
    return false;
}

I know it is too late, but I found this topic because I had the same problem.

And my solution may help other people.

The solution above didnt work well because it killed every running instance of Word, though it wasn't opened by the c# program but the user.

So this was not that userfriendly.

My code checks the processes before/after the creation of the Word.Application Object in c# and writes the IDs of the WINWORD Processes in List<int> then it compares the values in both List<int>. When a processID is not found in both List<int> it kills the process with this ID.

public List<int> getRunningProcesses()
{
    List<int> ProcessIDs = new List<int>();
    //here we're going to get a list of all running processes on
    //the computer
    foreach (Process clsProcess in Process.GetProcesses())
    {
        if (Process.GetCurrentProcess().Id == clsProcess.Id)
            continue;             
        if (clsProcess.ProcessName.Contains("WINWORD"))
        {
            ProcessIDs.Add(clsProcess.Id);
        }
    }
    return ProcessIDs;
}

Run this twice (one time before the creation of the Word.Application and once after).

 List<int> processesbeforegen = getRunningProcesses();
 // APP CREATION/ DOCUMENT CREATION HERE...
 List<int> processesaftergen = getRunningProcesses();

Then run killProcesses(processesbeforegen, processesaftergen);

 private void killProcesses(List<int> processesbeforegen, List<int> processesaftergen)
 {
    foreach (int pidafter in processesaftergen)
    {
        bool processfound = false;
        foreach (int pidbefore in processesbeforegen)
        {
            if (pidafter == pidbefore)
            {
                processfound = true;
            }
        }

        if (processfound == false)
        {
            Process clsProcess = Process.GetProcessById(pidafter);
            clsProcess.Kill();
        }
    }
 }

If you want to close whole word application, you can just call:

Word.Application app = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
if (app == null)
    return true;
app.Quit(false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!