c# Word Interop - 设置段落缩进

Rob*_*abe 2 c# ms-word office-interop paragraph

我需要以编程方式(在 C# 中)打开或关闭特定段落的悬挂缩进。

我创建了一个加载项,其中有一个按钮,单击该按钮后,我(尝试)执行此操作的代码。它是一个切换开关,因此第一次单击会添加悬挂缩进,第二次单击应将其删除。

在Word中,它是Paragraph>Indentation中的设置,后跟设置“ Special ”等于NoneHanging

在此输入图像描述

我对此的最佳尝试是使用以下代码:

foreach (Footnote rngWord in Globals.OSAXWord.Application.ActiveDocument.Content.Footnotes)
    rngWord.Range.ParagraphFormat.TabHangingIndent(
        rngWord.Range.ParagraphFormat.FirstLineIndent == 0 ? 1 : -1);
Run Code Online (Sandbox Code Playgroud)

它仅出于某种原因修改该段落的最后一行。我需要它是除第一行之外的所有挂起的行。我究竟做错了什么?

修改:

在此输入图像描述

注意 - 我实际上是在文档中的脚注上执行此操作。

Rob*_*abe 5

对于任何可能碰巧遇到此问题的人 - 以下是我的解决方法:

try
{
    // Loop through each footnote in the word doc.
    foreach (Footnote rngWord in Microsoft.Office.Interop.Word.Application.ActiveDocument.Content.Footnotes)
    {
        // For each paragraph in the footnote - set the indentation.
        foreach (Paragraph parag in rngWord.Range.Paragraphs)
        {
            // If this was not previously indented (i.e. FirstLineIndent is zero), then indent.
            if (parag.Range.ParagraphFormat.FirstLineIndent == 0)
            {
                // Set hanging indent.
                rngWord.Range.ParagraphFormat.TabHangingIndent(1);
            }
            else
            {
                // Remove hanging indent.
                rngWord.Range.ParagraphFormat.TabHangingIndent(-1);
            }
        }
    }
    // Force the screen to refresh so we see the changes.
    Microsoft.Office.Interop.Word.Application.ScreenRefresh();

}
catch (Exception ex)
{
    // Catch any exception and swollow it (i.e. do nothing with it).
    //MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您发布解决方案 (2认同)