2

How can I convert System.Drawing.Color to Microsoft.Office.Interop.Word.WdColorIndex?

I have done the code so far, but it's showing the error "overflow".

Here is the code which I have done

Color bgcolor = Color.FromArgb(Convert.ToInt32(innerText));
Microsoft.Office.Interop.Word.WdColorIndex wbgc = (Microsoft.Office.Interop.Word.WdColorIndex)(bgcolor.R + 0x100 * bgcolor.G + 0x10000 * bgcolor.B);
doc.Range(iRangeStart, iRangeEnd).HighlightColorIndex = wbgc;

How can I achieve this?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Jpaul
  • 278
  • 2
  • 11
  • 26

1 Answers1

4

WdColorIndex is an enumeration, not an object that defines a color system. This means that the value you can assign is limited by the enumeration elements, e.g. wdBlack or wdBlue and their underlying integer values.

The technique you are using is to be applied to a WdColor object instead of a WdColorIndex enumeration:

var wordColor = (Microsoft.Office.Interop.Word.WdColor)(bgcolor.R + 0x100 * bgcolor.G + 0x10000 * bgcolor.B);

Highlighting in a Word document is limited to a number of colors, as defined in the WdColorIndex enumeration. Therefore, you cannot simply convert any color to a Word color for highlighting. You have to pick one of the available values. See MSDN for WdColorIndex for possible values.

John Willemse
  • 6,608
  • 7
  • 31
  • 45
  • Thank you very much for the reply. I want to highlight the text using the above code . To highlight the text i think we have to use the the "HighlightColorIndex" property. or is there any other way to Highlight the text in Microsoft.Office.Interop? – Jpaul Apr 04 '13 at 04:40
  • JPaul, I have edited my answer to include highlighting in Word. – John Willemse Apr 04 '13 at 06:32
  • Thank you John. Now i understood that i just can't convert directly my InnerText value. I need to pick one color According to the wdcolor index. do you have any sample code for Highlighting the text using interop? As i have no much experience in using Microsoft office interop. Thank you once again for the valid suggestion.i wasted my lot of time by trying to convert. – Jpaul Apr 04 '13 at 10:15
  • [This CodeProject](http://www.codeproject.com/Tips/220074/Search-and-Highlight-the-Text-in-Word-through-Csha) example has C# code that you can use to get started, and you're welcome! – John Willemse Apr 04 '13 at 11:26
  • Can you explain what you did in (bgcolor.R + 0x100 * bgcolor.G + 0x10000 * bgcolor.B). Did you create a hexValue ? – pxm Feb 26 '14 at 14:28