I have the follow code:
===============================================================
using Microsoft.Office.Interop.PowerPoint;
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using PPTApplication = Microsoft.Office.Interop.PowerPoint.Application;
using PPTPresentation = Microsoft.Office.Interop.PowerPoint.Presentation;
namespace PPTTEST
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private DispatcherTimer timer = new DispatcherTimer();
public PPTApplication MyApplication { get; set; }
public StatusEnum Status { get; set; } = StatusEnum.Invalid;
public MainWindow()
{
InitializeComponent();
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (Status == StatusEnum.Invalid)
{
try
{
MyApplication = (PPTApplication)Marshal.GetActiveObject("PowerPoint.Application");
Status = StatusEnum.Ready;
MyApplication.SlideShowBegin += OnSlideShowBegin;
MyApplication.SlideShowEnd += OnSlideShowEnd;
}
catch
{
Status = StatusEnum.Invalid;
return;
}
}
try
{
///confirm the ppt is closed or not
string ss = MyApplication.Caption;
if (Status == StatusEnum.Ready)
{
///handle the job1
}
else
{
///handle the job2
}
}
catch(COMException ex)
{
Status = StatusEnum.Invalid;
MyApplication = null;
return;
}
}
private void OnSlideShowEnd(PPTPresentation Pres)
{
if (Status == StatusEnum.Running)
{
Status = StatusEnum.Ready;
}
}
private void OnSlideShowBegin(SlideShowWindow SlideShowWindow)
{
if (Status == StatusEnum.Ready)
{
Status = StatusEnum.Running;
}
}
public enum StatusEnum
{
Invalid, Ready, Running
}
}
}
However, it faces some problems. When I running the code, then open the ppt and press F5 quickly. The event OnSlideShowBegin can't be trigger. But if I wait for at least 5 second before press F5, the event OnSlideShowBegin can be trigger. What is this reason?