我的VSTO
加载项提供了一个功能区按钮,单击该按钮时,将调用ObjButtonAddFoo_Click
该按钮将所选文本替换为文字字符串:
private bool ReplaceText(string textToInsert)
{
bool retval = false;
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
// if (currentSelection.ContainsTrailingParagraphMark)
// {
// retval = true;
// }
currentSelection.Range.Text = textToInsert;
currentSelection.EndKey(WdUnits.wdStory);
return retval;
}
private void ObjButtonAddFoo_Click(object sender, RibbonControlEventArgs e)
{
if (ReplaceText("REPLACEMENT TEXT"))
{
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
currentSelection.TypeParagraph();
}
}
问题
注意:对于下面的屏幕截图,文件->选项->显示->显示所有格式标记被选中。
如果用户选择包含结尾段落标记的文本:
然后在执行代码时段落标记会丢失currentSelection.Range.Text = textToInsert
。因此,如果选择包含结尾段落标记,我想通过执行替换它currentSelection.TypeParagraph()
我尝试查看 currentSelection.Paragraphs.Count,但无论选择是否包含段落标记,它的值为 1。
我还尝试了如何:在创建范围时以编程方式排除段落标记中描述的技术,但是如果选择不包括尾随段落标记,则保留最初选择的文本的最后一个字符。换句话说,我仍然需要知道选择中是否有尾随段落标记。
private bool ReplaceText(string textToInsert)
{
bool retval = false;
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
// if (currentSelection.ContainsTrailingParagraphMark)
// {
// retval = true;
// }
//Remove the paragraph mark from the range to preserve it
object charUnit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
object move = -1; // move left 1
currentSelection.MoveEnd(ref charUnit, ref move);
currentSelection.Range.Text = textToInsert;
currentSelection.EndKey(WdUnits.wdStory);
return retval;
}
在我的ReplaceText
方法中,如何确定 currentSelection 是否有尾随段落标记。或者,执行时如何保留段落标记currentSelection.Range.Text = textToInsert
?