如何以编程方式在ms word中设置文本样式? [英] How programatically set text styling in ms word?

查看:113
本文介绍了如何以编程方式在ms word中设置文本样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:
我正在处理MS Word文档的内容.我正在根据某些规则更改某些单词的颜色.每次KeyPress事件都会出现单词着色.

Situation:
I'm working with MS Word document's contents. I'm changing color of some words according to some rule. Words coloring occurs on each KeyPress event.

问题:
当用户键入满足我的规则键入的单词的单词时,该单词变为彩色,并感染将来的文本,该单词将在带有颜色的文本之后立即键入.但是将来的文字可能无法满足该规则.一方面,刚键入的文本不应着色,但另一方面,它已经着色了,因为不幸的是,它刚好在着色文本之后出现,并且被样式感染了.

Problem:
When user types word which satisfies my rule typed word become colored and infects future text which will be typed right after colored text. But future text may not satisfay the rule. From the one hand, just typed text shouldn't be colored but from the other hand it already colored because it unfortunately goes right after colored text and was infected by it's style.

问题:如何获取与当前光标位置相对应的Word.Range对象并将字体颜色明确设置为中性默认颜色?我尝试过

Question: How grab Word.Range object corresponding to the current cursor position and expicitly set font color to neutral default color? I tried

Word.Range r = app.Application.ActiveDocument.Range(
app.Application.ActiveDocument.Bookmarks[@"\Sel"].Range.Start,
app.Application.ActiveDocument.Bookmarks[@"\Sel"].Range.End);
r.Font.Color = WdColor.wdColorBlack;

Word.Range r = app.Application.ActiveDocument.Bookmarks[@"\Sel"].Range;
r.Font.Color = WdColor.wdColorBlack;

推荐答案

要设置默认颜色,您有两个选择:

To set default color you have two options:

//really default color:
r.Font.ColorIndex = Word.WdColorIndex.wdAuto;

//assuming default is black- set it to black
r.Font.ColorIndex = Word.WdColorIndex.wdBlack;

修改.要将颜色重新设置为选定范围内的默认颜色,您可以尝试以下代码:

Edit. To set the color back to default as of selected range you could try this code:

Word.Application.Selection.Font.ColorIndex = Word.WdColorIndex.wdAuto;

它不引用活动文档,而是引用应用程序的Selection.运行后,下一个单词将以默认颜色书写.

It doesn't refer to active document but to Selection of the application. After you run it next words are written in default color.

这篇关于如何以编程方式在ms word中设置文本样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆