0

我的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

4

1 回答 1

0

我把这弄得太难了。我所要做的就是询问选择的最后一个字符,看看它是否是段落标记。

    private void ReplaceText(string textToInsert)
    {
        // https://docs.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-exclude-paragraph-marks-when-creating-ranges?view=vs-2019

        Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;

        // if current selection has a trailing paragraph mark, then 
        // modify the selection to omit it before replacing the text
        if (currentSelection.Range.Text.Substring(currentSelection.Range.Text.Length-1, 1).Equals("\r"))
        {
            object charUnit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
            object move = -1;
            currentSelection.MoveEnd(ref charUnit, ref move);
        }

        currentSelection.Range.Text = textToInsert;
    }
于 2019-07-19T18:04:50.640 回答