1

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

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

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

4

2 回答 2

0

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

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);
        }    
 }
于 2012-07-11T02:20:41.103 回答
-1

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

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

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

为我工作。对你起作用吗?

于 2012-07-12T12:43:48.857 回答