为什么在从C#添加新文本时变粗不起作用?

时间:2015-04-24 10:22:07

标签: c# ms-word interop

我想将C#中的文本添加到Winword文档中,然后在关闭时变为粗体。

使用此选项, abc 以粗体显示。然后以编程方式关闭粗体,因此当直接在Winword中键入时,以下文本显示为unbold。

{
    objWinWordControl.document.Application.Selection.Font.Bold = 1;
    objWinWordControl.document.Application.Selection.Text = "abc";
    objWinWordControl.document.Application.Selection.EndKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove);

    objWinWordControl.document.Application.Selection.Font.Bold = 0;
    // continue typing text in Winword now, the text isn't bold
}

虽然大胆已经关闭,但我在这里获得了大胆的 abcxyz

{
    objWinWordControl.document.Application.Selection.Font.Bold = 1;
    objWinWordControl.document.Application.Selection.Text = "abc";

    objWinWordControl.document.Application.Selection.EndKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove);

    objWinWordControl.document.Application.Selection.Font.Bold = 0;

    // this text is bold, although bold  had been turned off
    objWinWordControl.document.Application.Selection.Text = "xyz"; 
}

为什么以编程方式添加“xyz”时会加粗?

1 个答案:

答案 0 :(得分:0)

我现在找到了这样的解决方法:

{
    object start = 0;
    object end = 0;

    Word.Range rng = objWinWordControl.document.Range(ref start, ref end);
    rng.Text = "abc";
    rng.Font.Bold = 1;

    start = rng.Text.Length;
    end = rng.Text.Length;

    rng = objWinWordControl.document.Range(ref start, ref end);
    rng.Text = "xyz";
    rng.Font.Bold = 0;
}

但与之相比:

 objWinWordControl.document.Application.Selection.Text = "abc";

表现非常糟糕。