Alexandru Alexandru - 2 months ago 11
C# Question

Making a Shape top-most

In my Word add-in, I have a Word

Document
object which contains a particular
Section
. In this
Section
, I append a
Shape
:

var shape = section.Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, "Example text...", "Calibri", 72, MsoTriState.msoFalse, MsoTriState.msoFalse, 0, 0, section.Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range) as Shape;


My issue is that some Word document templates have images or other things that appear over top of my shape. Originally, I thought that setting the Z order would be enough to fix this:

shape.ZOrder(MsoZOrderCmd.msoBringToFront);


It did not. So my question is, how can I absolutely set the Z order of my
Shape
, or in other words, what else would I have to do to set in order to make my
Shape
such that it becomes the top-most thing you see in the document (meaning, that it appears above all of the other things)?

Answer

I finally figured out why these methods weren't working:

shape.ZOrder(MsoZOrderCmd.msoBringInFrontOfText);
shape.ZOrder(MsoZOrderCmd.msoBringToFront);

The problem was that my Shape object was defined within a HeaderFooter section, but the shape that was displaying over top of it was defined within the Document itself. Z-ordering is only relative to the section you are in (document, header, footer, etc.).

So instead of this code to add the shape to a particular section:

var shape = section.Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, "Example text...", "Calibri", 72, MsoTriState.msoFalse, MsoTriState.msoFalse, 0, 0, section.Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range) as Shape;
shape.ZOrder(MsoZOrderCmd.msoBringInFrontOfText);
shape.ZOrder(MsoZOrderCmd.msoBringToFront);

I used this code to add it to my document directly and then apply Z-ordering to it, and it actually worked. It appeared above all of the other objects which were a part of my template:

var shape = document.Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, "Example text...", "Calibri", 72, MsoTriState.msoFalse, MsoTriState.msoFalse, 0, 0) as Shape;
shape.ZOrder(MsoZOrderCmd.msoBringInFrontOfText);
shape.ZOrder(MsoZOrderCmd.msoBringToFront);