office DocumentBeforeSave 事件仅在几秒钟后绑定后才有效
office DocumentBeforeSave events only work after bind in few seconds
我正在开发一项功能,即在每次保存打开的单词时创建一个备份。
我正在使用打击代码挂接到word进程并为其绑定事件,word由进程打开。
officeApplication = (Application)Marshal.GetActiveObject("Word.Application").
officeApplication.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(App_BeforeSaveDocument);
在App_BeforeSaveDocument
我完成了我的工作。
我 officeApplication
正确,绑定事件很好,当我单击保存在 word 中时,事件完美触发。
问题是,几秒钟后(可能是 30 秒),事件将不再触发,无论是单击保存还是保存我们或关闭文档。
有什么建议吗?
查了很多,还是找不到原因。我决定用一个技巧来接近它。
首先在绑定事件中开启线程:
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);
}
}
而且效果很好。不要记得在文档关闭或异常发生时中止线程。
我正在开发一项功能,即在每次保存打开的单词时创建一个备份。 我正在使用打击代码挂接到word进程并为其绑定事件,word由进程打开。
officeApplication = (Application)Marshal.GetActiveObject("Word.Application").
officeApplication.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(App_BeforeSaveDocument);
在App_BeforeSaveDocument
我完成了我的工作。
我 officeApplication
正确,绑定事件很好,当我单击保存在 word 中时,事件完美触发。
问题是,几秒钟后(可能是 30 秒),事件将不再触发,无论是单击保存还是保存我们或关闭文档。
有什么建议吗?
查了很多,还是找不到原因。我决定用一个技巧来接近它。
首先在绑定事件中开启线程:
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);
}
}
而且效果很好。不要记得在文档关闭或异常发生时中止线程。