VSTO Word插件:set_Style(参考代码),忽略背景色

时间:2019-01-31 12:43:40

标签: c# ms-word vsto office-addins

当我尝试通过以下方式将所选内容的样式设置为代码样式时:

Microsoft.Office.Interop.Word.Application oWordApp = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
Microsoft.Office.Interop.Word.Selection currentSelection = oWordApp.Selection;

object codeStyle = "Code";
// this disrespects the background
currentSelection.set_Style(ref codeStyle);

它忽略了背景色(浅蓝色):

enter image description here

当我将其应用于 Range 时,它会在整个段落中使用:

Microsoft.Office.Interop.Word.Application oWordApp = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
Microsoft.Office.Interop.Word.Selection currentSelection = oWordApp.Selection;

// this sets the style to the whole paragraph, but i want the range only
currentSelection.Range.set_Style(ref codeStyle);

enter image description here

定义的“代码”是:

enter image description here

我只想要代码样式的单词/选择“攻击者”。我在做什么错?当我录制一个宏时,它给了我这个:

Selection.Style = ActiveDocument.Styles("Code")

但这对我没有多大帮助...

1 个答案:

答案 0 :(得分:0)

我发现了问题。您可以在样式后面附加样式库:

Microsoft.Office.Interop.Word.Application oWordApp = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
Microsoft.Office.Interop.Word.Selection currentSelection = oWordApp.Selection;

object codeStyle = "Code Char"; //appending Char made its job!
currentSelection.Range.set_Style(ref codeStyle);