office DocumentBeforeSave事件仅在几秒钟内绑定后才能工作

问题描述 投票:0回答:1

我正在开发一项功能,即每次保存一个打开的单词时创建备份。我正在使用打击代码来挂接到单词进程并将事件绑定到它,该单词由进程打开。

officeApplication = (Application)Marshal.GetActiveObject("Word.Application").
officeApplication.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(App_BeforeSaveDocument);

App_BeforeSaveDocument,我做了我的工作。

我得到officeApplication正确,绑定事件很好,当我点击保存在单词中,事件触发完美。问题是,几秒钟后(可能是30秒),事件将不会再触发,无论是单击保存还是保存我们或关闭文档。

有什么建议吗?

c# ms-word hook office-interop
1个回答
0
投票

经过大量的研究,我仍然找不到原因。我决定使用一个技巧来接近它。

首先,在绑定事件中打开一个线程:

static void App_BeforeSaveDocument(Microsoft.Office.Interop.Word.Document document, ref bool saveAsUI, ref bool cancel)
            {
                if (th != null)
                    th.Abort();
                th = new Thread(backupOnSave);
                th.IsBackground = true;
                th.Start(document);
            }

然后在线程中执行无限循环:

internal static void backupOnSave(object obj)
        {
            try
            {
                Application app = obj as Application;
                if (app == null || app.ActiveDocument == null)
                {
                    return;
                }
                Microsoft.Office.Interop.Word.Document document = app.ActiveDocument;
                if (!tempData.ContainsKey(document.FullName))
                    return;
                var loopTicks = 2000;

                while (true)
                {
                    Thread.Sleep(loopTicks);
                    if (document.Saved)
                    {
                        if (!tempData.ContainsKey(document.FullName))
                            break;
                        var p = tempData[document.FullName];
                        var f = new FileInfo(p.FileFullName);

                        if (f.LastWriteTime != p.LastWriteTime)//changed, should create new backup
                        {
                            BackupFile(p, f);
                            p.LastWriteTime = f.LastWriteTime;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.write(ex);
            }
        }

它工作正常。不记得在文档关闭或异常发生时中止线程。

© www.soinside.com 2019 - 2024. All rights reserved.