Im looking for a way to insert an MS Word Shape at cursor position. At the moment I have the following code which inserts a shape at a predetermined location:
Microsoft.Office.Interop.Word.Range CurrRange = Globals.ThisAddIn.Application.Selection.Range;
//Get the id of the MS Word shape to be inserted
int shapeId = (int)MsoAutoShapeType.msoShapeRoundedRectangle;
//Get the value of the name attribute from the selected tree view item
string nodeText = treeViewItem.GetAttribute("name");
//Add a new shape to the MS Word designer and set shape properties
var shape = CurrRange.Document.Shapes.AddShape(shapeId, 170, 200, 100, 20);
shape.AlternativeText = String.Format("Alt {0}", nodeText);
shape.TextFrame.ContainingRange.Text = nodeText;
shape.TextFrame.ContainingRange.Font.Size = 8;
The location where the shape gets inserted is hardcoded:
This can be seen from the 2nd and 3rd parameters of the AddShape() method:
170 = position measured in points to the left edge of the autoshape
200 = position measured in points to the top edge of the autoshape
I’ve had a look at the properties and methods of my Range object but cannot seem to find any which store the position values which I require.
The final parameter to AddShape is an Anchor, which expects a range object. Try passing your range into that:
Update: It looks like there is a bug in Word 2010 documents that it doesn’t respect the Anchor. Save the document as a .doc file and test again, it does anchor it to the beginning of the paragraph if you do that. The link above is just to the microsoft forums, I could not find the connect bug report for the issue.
A workaround would be to specify the top and left based on the location of the selection: