设置word颜色
就是操作Word的时候Microsoft.Office.Interop.Word.WdColor与Color之间的映射关系。
开始看了一个帖子这么写的:
int p= color.Argb();
Microsoft.Office.Interop.Word.WdColor=(Microsoft.Office.Interop.Word.WdColor) int;
这个强人就是胡说八道啊
事实上,我们以ARGB共4字节来分析吧
WdColor Color
======================= =======================
Byte3 Byte2 Byte1 Byte0 Byte3 Byte2 Byte1 Byte0
0x00 B G R 0xff R G B
可见,WdColor没有考虑透明度A<这个在Word里面实现不了>,而且RGB的位置也不对
为了转换这2个,首先应该了解1个问题
(1)WdColor是枚举,而Color是类
也就是说Color=new Color(A,R,G,B),其中四个参数是可以在0~255任意选择的。
而WdColor只有60个。也就是说,就算格式转换过来了,也无法正常的设置WdColor的值。
那怎么办呢/
Microsoft.Office.Interop.Word.WdColor GetColor(Color c)
{
UInt32 R=0x1,G=0x100,B=0x10000;
return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);
}
就可以了。
例子如下:
namespace WindowsApplication92
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
app = new Microsoft.Office.Interop.Word.Application();
docs = app.Documents;
doc = docs.Add(ref missing, ref missing, ref missing, ref missing);
app.Visible = true;
doc.Activate();
doc.Activate();
}
Microsoft.Office.Interop.Word.Application app;
Microsoft.Office.Interop.Word.Documents docs;
Microsoft.Office.Interop.Word.Document doc;
object missing = System.Reflection.Missing.Value;
private void button1_Click(object sender, EventArgs e)
{
ColorDialog c = new ColorDialog();
if (c.ShowDialog() == DialogResult.OK)
{
Color color = c.Color;
app.Selection.Font.Color = GetColor(color);
app.Selection.TypeText(DateTime.Now.ToLongTimeString());
app.Selection.TypeParagraph();
}
}
Microsoft.Office.Interop.Word.WdColor GetColor(Color c)
{
UInt32 R=0x1,G=0x100,B=0x10000;
return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);
}
private void button2_Click(object sender, EventArgs e)
{
object x1 = true;
object x2 = false;
object x3="c://123.doc";
doc.SaveAs(ref x3, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.Close(ref x1,ref missing, ref missing);
app.Quit(ref x1,ref missing, ref missing);
}
}
}