7

目前,我正在使用此代码来获取 MS Word 打开文档的列表:

List<string> doc_list = new List<string>();
try
{
    Microsoft.Office.Interop.Word.Application WordObj;
    WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
    for (int i = 0; i < WordObj.Windows.Count; i++)
    {
        object idx = i + 1;
        Window WinObj = WordObj.Windows.get_Item(ref idx);
        doc_list.Add(WinObj.Document.FullName);
    }
}
catch
{
    // No documents opened
}

如果文档已经“直接”打开,即双击它们,它可以正常工作。但是,我注意到如果我直接从 C# 代码打开 MS Word 文档,例如:

Microsoft.Office.Interop.Word.Application word_app = new Microsoft.Office.Interop.Word.Application();

object inputFile = selected_doc;    // "selected_doc" contains the document name
object confirmConversions = false;
object readOnly = false;
object visible = true;
object missing = Type.Missing;

Document doc = word_app.Documents.Open(
    ref inputFile, ref confirmConversions, ref readOnly, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref visible,
    ref missing, ref missing, ref missing, ref missing);

初始代码找不到以这种方式打开的任何文档,但我需要检测它。为什么找不到?如何修改代码以便找到从 C# 打开的文档?

4

1 回答 1

5

在第一个代码中,您可以在打开的 Word 实例中获取已打开文档的列表

Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");

在代码的第二部分,您使用 Word 的New实例创建一个新文档

Microsoft.Office.Interop.Word.Application word_app = new Microsoft.Office.Interop.Word.Application();

所以文件不能被两个 Word 实例打开和列出。

如果您希望第一种方法能够获取文件,您可以尝试从 Word 的当前实例打开文件:

Microsoft.Office.Interop.Word.Application word_app;
word_app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application")

object inputFile = selected_doc;    // "selected_doc" contains the document name
object confirmConversions = false;
object readOnly = false;
object visible = true;
object missing = Type.Missing;

Document doc = word_app.Documents.Open(
    ref inputFile, ref confirmConversions, ref readOnly, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref visible,
    ref missing, ref missing, ref missing, ref missing);
于 2013-09-19T10:34:51.503 回答