delphi 如何让LibreOffice在打开后自动关闭?

toe95027  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(232)

我试图打开LibreOffice Calc,然后使用ole自动化再次关闭它。
问题是,虽然我可以打开电子表格,但当我试图关闭它时,只有电子表格窗口关闭,soffice进程仍保留在任务管理器中,因此LibreOffice没有正确关闭。
下面是我用来打开一个电子表格的 Delphi 代码:

Office: Variant;
frame: Variant;
Desktop: Variant;
comp: Variant;
Doc: Variant;
args: Variant;

Office := CreateOleObject('com.sun.star.ServiceManager');
desktop := Office.CreateInstance('com.sun.star.frame.Desktop');
args := VarArrayCreate([0,1], varVariant);
Doc := desktop.loadComponentFromURL('private:factory/scalc', '_blank', 0, args);

电子表格现在已打开,一切正常,现在我想关闭它,所以我尝试了以下方法,但无法正常工作:

Doc.Dispose;
  frame := Desktop.FindFrame('_blank', 0);
  frame.Dispose;
  Desktop.Dispose;
  Office.Dispose;

我也试过这哪也不正常:

Doc.Close(True);
  sleep(500);
  Desktop.Dispose;
  Office.Dispose;

在这两种情况下,程序窗口都关闭,但soffice进程仍保留在任务管理器中。这是在Windows 7上用LibreOffice 6测试的。
我确实发现了这个应该有用的东西:

xModifiable = (XModifiable)xComponent;
xModifiable.setModified(false);
xCloseable = (XCloseable)xComponent;
xCloseable.close(true);

// This closes all instances, even ones you didn't create
// If you don't write this, you'll find 'soffice.bin' still lingering in taskmgr
XDesktop xDesktop = (XDesktop)xCLoader;
if(xDesktop != null)
        xDesktop.terminate();

但我不能在 Delphi 中编译它。

moiiocjp

moiiocjp1#

这个例子中的解是Desktop.Terminate。这会导致LibreOffice关闭,其进程终止,尽管任何修改过的文档都应该在此之前关闭。然而,根据“doug”在2015年www.example.com上的一篇文章ask.libreoffice.org:
要创建干净的关机,并且以后不提示恢复文件,在terminate命令之前需要等待很长时间,因为LibreOffice中存在明显的争用情况。您的等待时间可能需要更长,也可能更短。因此,以干净的terminate命令结束的序列将是:

Doc.Close(True);
Sleep(400);
Desktop.Terminate;

如果修改了当前文档,terminate命令会自动调用,并生成保存提示,但由于存在已记录的争用情况,关闭通常是不干净的。
[code已修改以适合问题中的示例]

相关问题