【发布时间】:2014-06-26 03:05:39
【问题描述】:
我有一个脚本可以从我的应用程序中打开 Powerpoint 并导出所有幻灯片。 之后,我需要关闭应用程序。
我试过没有任何运气。你能帮忙吗?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Powerpoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System.Runtime.InteropServices;
namespace PresentrBuilder
{
class PowerpointConverter
{
public static void Convert(String file, String safeFile)
{
Powerpoint.Application PP;
Powerpoint.Presentation Presentation;
PP = new Powerpoint.ApplicationClass();
PP.Visible = MsoTriState.msoTrue;
PP.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMinimized;
Presentation = PP.Presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
// Voor elke slide, exporteren
String exportSlidesPath = Path.Combine(Properties.Settings.Default.CacheDir, @"presentatienaam1\slides");
// Kijk of de directory bestaat
if (!Directory.Exists(exportSlidesPath))
{
Directory.CreateDirectory(exportSlidesPath);
}
// Kijk of er al bestanden in de directory staan
// Zo ja: verwijderen
String[] files = Directory.GetFiles(exportSlidesPath, "*.png");
if (files.Length > 0)
{
foreach (string fileName in files)
{
File.Delete(Path.Combine(exportSlidesPath, fileName));
}
}
// Elke slide exporteren
foreach (Slide slide in Presentation.Slides)
{
slide.Export(Path.Combine(exportSlidesPath, "slide_" + slide.SlideIndex + ".png"), "PNG", 1024, 768);
Marshal.ReleaseComObject(slide);
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(PP.Presentations);
Marshal.ReleaseComObject(Presentation.Slides);
Presentation.Close();
Marshal.FinalReleaseComObject(Presentation);
PP.Quit();
Marshal.FinalReleaseComObject(PP);
}
}
}
【问题讨论】:
-
您已经编辑了上面的代码,但仍然不正确。您调用 PP.Presentations(和 Presentation.Slides)两次,一次使用它们,然后一次释放引用。但是它不是这样工作的——每次调用它们时,都会创建另一个引用。您需要调用它们一次,并将引用存储在一个变量中,然后您可以释放(根据安德烈的回答)。
-
在完成此方法调用后,尝试从另一个方法调用 Collect and Wait
标签: c# visual-studio com powerpoint