Word VSTO插件开发:如何在RGB格式的范围中找到文本的颜色



我正在使用C#为MS Word开发一个插件。我需要在RGB格式的Range对象中找到文本的颜色。

  • 我尝试使用Range.Font.Color,它应该给出RGB值。但我从中得到了负值和超出范围的值
  • Range.Font.TextColor给了我一个NotImplemented异常

我正在使用Visual Studio 2010。请帮帮我。

这里有一个小的测试方法,可以将字体颜色的html样式标记放入文档中(我需要为粗体和斜体做这件事,只是想看看我是否能得到颜色)如果你摆弄它,你可能会得到你需要的东西,它是Word 的c#vsto

private void TEST()
{
        Range currentWord = Globals.ThisAddIn.Application.ActiveDocument.Words.First;
        object collapseStartObj = WdCollapseDirection.wdCollapseStart;
        object oText = "";
        object oMiss = System.Reflection.Missing.Value;
        object oFindStop = WdFindWrap.wdFindStop;
        object oCountOne = 1;
        object oWordUnit = WdUnits.wdWord;
        int count = 0;
        while (currentWord != null)
        {
            count++;
            currentWord.Find.Font.Bold = currentWord.Font.Bold;
            currentWord.Find.Font.Italic = currentWord.Font.Italic;
            currentWord.Find.Font.ColorIndex = currentWord.Font.ColorIndex;
            string text = currentWord.Font.ColorIndex.ToString();
            string thatColor = Regex.Replace(text, @"d", ""); //remove any digits
            string simpleColor = Regex.Replace(thatColor, "wd", "");//remove the wd
            //MessageBox.Show(simpleColor); //for testing
            currentWord.Find.Forward = true;
            currentWord.Find.Format = true;
            currentWord.Collapse(ref collapseStartObj);
            currentWord.Find.Execute(ref oText, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oFindStop, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss, ref oMiss);
            if (simpleColor != "NoHighlight")
            {
                try
                {
                    string theText = currentWord.Duplicate.Text;
                    string thatText = Regex.Replace(theText, "r", "");//get rid of carriage return
                    currentWord.Find.Execute(FindText: thatText, Format: true, ReplaceWith: "<font style = "color:" + simpleColor + "">^&</font>", MatchWildcards: true, Replace: Word.WdReplace.wdReplaceOne);
                }
                catch { }
            }
        currentWord = currentWord.Next(ref oWordUnit, ref oCountOne);
        }    
 }

使用Don Rotman的扩展方法将Range.Font.Color转换为System.Drawing.Color以将Word 2007的WdColor转换为.NET颜色类

 MSWord.WdColor color = app.Selection.Range.Font.Color;
 Color myColor = color.ToColor(); //ToColor is the extension method described in link

现在,即使Range.Font.Color没有返回像WdOrange这样的实际枚举值,而是返回像:-65245889这样的值,它也将转换为包含所有RGB数据的System.Drawing.Color对象。

对我有用。对你有用吗?

最新更新