开发者

How to know the background color of the ms word document using C#

开发者 https://www.devze.com 2023-01-17 12:02 出处:网络
I\'m using C# office (word) automation by Microsoft Office 12.0 Object Library. And I opened a \"1.doc\" file and I need to check if this file has a background color or not.

I'm using C# office (word) automation by Microsoft Office 12.0 Object Library. And I opened a "1.doc" file and I need to check if this file has a background color or not.

Note: I mean the background color applied by the following steps:

  • Open MS Word 2003, and open a document.
  • Go to : Format menu -> Background and choose color.

And here what I have in C#:

Object oMissing = System.Reflection.Missing.Value;

        //OBJECTS OF FALSE AND TRUE
        Object oTrue = true;
        Object oFalse = false;
        Object fileName = "c:\\1.doc";

开发者_如何转开发        //CREATING OBJECTS OF WORD AND DOCUMENT
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document();

        //MAKING THE APPLICATION VISIBLE
        oWord.Visible = true;

        //ADDING A NEW DOCUMENT TO THE APPLICATION
        oWordDoc = oWord.Documents.Open(
            ref fileName, ref oMissing, ref oFalse, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oTrue, ref oMissing, ref oMissing, ref oMissing);
        Console.WriteLine(oWordDoc.Background.Fill.ForeColor.RGB);
        Console.WriteLine(oWordDoc.Background.Fill.BackColor.RGB);

I do not know if the ForeColor or BackColor represent the color that i need, I tried to choose different background colors and executed the above code and every time I got a different integer value like (10092543, 255 for red, ....) but It does not make sense, and the BackColor is never changed and fixed at the value (16777215). Many Thanks.


You are on the right track. The page background is indeed the foreground color of the Background object. The different values that you see correspond to the integer representation of the RGB color values.

If you are interested in the different color components you can use the following code:

Color color = Color.FromArgb(oWordDoc.Background.Fill.ForeColor.RGB);
int red = color.R;
int green = color.G;
int blue = color.B;

Update

The color used by the Office object model seems to use a different internal format than System.Drawing.Color so the channels might get mixed up when you use the above sample code (I forgot to check the actual format of Word.ColorFormat.RGB).

You can always retrieve the different color channels yourself using the following code:

int wordColor = oWordDoc.Background.Fill.ForeColor.RGB;
int channel1 = (int)((wordColor >> 0x10) & 0xffL);
int channel2 = (int)((wordColor >> 0x8) & 0xffL);
int channel3 = (int)(wordColor & 0xffL);
0

精彩评论

暂无评论...
验证码 换一张
取 消