PowerPoint Interop: copy-pasting a shape crashes if done too fast

626 Views Asked by At

I'm using the Microsoft.Office.Interop.PowerPoint in a C#/.NET program in order to automate some operation on a PPTX file.

I'm trying to create a copy of an existing Shape in the presentation by using this code:

var shape = slide.Shapes[1];
shape.Copy();
var newShape = targetSlide.Shapes.Paste();

however, the Paste() instruction is unreliable, it sometimes works but sometimes (apparently at random) throws the following exception:

ERROR: System.Runtime.InteropServices.COMException (0x80048240): Shapes (unknown member) : Invalid request. Clipboard is empty or contains data which may not be pasted here. in Microsoft.Office.Interop.PowerPoint.Shapes.Paste()

After fiddling around for a bit and searching online, I found out that the problem is that the .Copy() instruction is apparently asynchronous, basically when it returns there is no guarantee that the shape object has actually been copied to the clipboard. In fact, adding a:

Thread.Sleep(1000);

between the Copy() and Paste() instructions fixes the problem.

However, sleeping is not a proper solution, it slows down the program greatly and there is no way of knowing if you have set the sleep time too high or too low.

My question is: is there a more reliable way to wait for the copy to be "ready" before pasting?

1

There are 1 best solutions below

0
On

I might be late but here is my solution: It happened to me when I was iterating over shapes in a slide. Copying each and pasting each sometimes throws the error you mentioned. What I did is that I copied the shapes all at once.

CurrentSelection.SlideRangle.Shapes.Copy();
targetPresentation.Slides[index].Shapes.Paste();

Another ideea would be to copy the whole slide:

CurrentSelection.SlideRangle.Shapes.Copy();

and then

Globals.ThisAddIn.Application.CommandBars.ExecuteMso("PasteSourceFormatting");

you can also use "PasteDestinationTheme"