在光标位置插入单词形状

本文关键字:单词形 插入 位置 光标 | 更新日期: 2023-09-27 18:18:21

我正在寻找一种方法来插入一个MS Word形状在光标位置。目前,我有以下代码在预定位置插入形状:

        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;

形状插入的位置是硬编码的:

这可以从AddShape()方法的第2、3个参数看出:

170 =以点为单位测量到autoshape左边缘的位置

200 =以点为单位测量到autoshape上边缘的位置

我已经看了一下我的范围对象的属性和方法,但似乎找不到任何存储我需要的位置值。

在光标位置插入单词形状

AddShape的最后一个参数是一个Anchor,它需要一个范围对象。尝试将您的范围传入:

var shape = CurrRange.Document.Shapes.AddShape(shapeId, 0, 0, 100, 20,CurrRange);

更新:看起来Word 2010文档中有一个错误,它不尊重锚。将文档保存为.doc文件并再次测试,如果您这样做,它会将其锚定到段落的开头。上面的链接只是到微软论坛,我找不到这个问题的连接错误报告。

一个解决方法是根据选择的位置指定顶部和左侧:

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 = "Hello World";
var left = Globals.ThisAddIn.Application.Selection.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdHorizontalPositionRelativeToPage);
var top = Globals.ThisAddIn.Application.Selection.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdVerticalPositionRelativeToPage);
//Add a new shape to the MS Word designer and set shape properties
var shape = CurrRange.Document.Shapes.AddShape(shapeId, left, top, 100, 20);
shape.AlternativeText = String.Format("Alt {0}", nodeText);
shape.TextFrame.ContainingRange.Text = nodeText;
shape.TextFrame.ContainingRange.Font.Size = 8;