2011-12-19 80 views
0

我正在寻找一种方法在光标位置插入MS Word形状。目前我有以下代码在预定位置插入一个形状:在光标位置插入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()方法:

在点测量到自选

200 =在位置点处测量到的自选图形的顶部边缘的左边缘170 =位置

我已经看过我的Range对象的属性和方法,但似乎无法找到任何存储我需要的位置值的地方。

回答

2

AddShape的最后一个参数是一个Anchor,它需要一个范围对象。尝试通过你的范围成:

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

更新:它看起来像有,因为它不尊重锚的Word 2010个文档bug。将文档另存为.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; 
+0

我已经尝试过这一点,它不work.The形状仍插在同一位置 – 2011-12-20 05:19:25

+0

我用微软论坛上的一些信息更新了我的答案。 – 2011-12-20 14:15:59

+0

我在msdn上也遇到过这个帖子 - http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/53d9baff-c10c-4655-822a-4c7a1b0fa885/然而,left和top值总是需要增加70,否则形状插入光标左上方几厘米......这很奇怪,我不完全确定它为什么必须完成,但它确实似乎工作。谢谢为了努力,标记为已回答 – 2011-12-21 05:24:20