2012-07-09 159 views
1

我正在开发一个使用C#的MS Word插件。我需要以RGB格式在Range对象内找到文本的颜色。Word VSTO插件开发:如何在RGB格式的Range中查找文本的颜色?

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

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

+0

您是否愿意将范围保存为XML,然后查询w:color,并将其十六进制值转换为RGB?如果一个范围。 – JohnZaj 2012-07-10 13:24:47

+0

是的,我也有这个选项。您能否给我提供一些链接,以便我可以阅读有关使用Word Open XML的内容? – Aghoree 2012-07-11 16:21:54

+1

从这里开始:http://msdn.microsoft.com/en-us/library/bb497448.aspx – JohnZaj 2012-07-12 02:19:45

回答

0

这里有一个小测试方法,可以将HTML样式标签的字体颜色放入文档中(我需要为粗体和斜体做这件事,只是想看看我能不能获得颜色)也许能得到你所需要的是C#VSTO的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); 
     }  
} 
+0

此代码仅显示红色,灰色等有限的颜色。此外,还显示了“不亮”等情况。我需要RGB格式的颜色。 – Aghoree 2012-07-11 15:40:57

0

转换一个Range.Font.Color使用唐罗特曼的扩展方法一个System.Drawing.Color为Converting Word 2007’s WdColor to .NET Color Class

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对象。

适合我。对你起作用吗?