2011-03-09 42 views
6

我创建使用C#PowerPoint演示文稿:如何更改C#中PowerPoint中TextRange的字体颜色?

PowerPoint.Application powerpointApplication; 
PowerPoint.Presentation pptPresentation; 
PowerPoint.Slide Slide; 

// Create an instance of PowerPoint. 
powerpointApplication = new PowerPoint.ApplicationClass(); 

// Create a PowerPoint presentation. 
pptPresentation = powerpointApplication.Presentations.Add(
Microsoft.Office.Core.MsoTriState.msoTrue); 


// Create empty slide 
Slide = pptPresentation.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutBlank); 

TextRange objTextRng = objSlide.Shapes[1].TextFrame.TextRange; 
objTextRng.Text = "Remote sensing calendar 1"; 
objTextRng.Font.Name = "Comic Sans MS"; 
objTextRng.Font.Size = 48; 
// TODO: change color 
// objTextRng.Font.Color 



// Save presentation 
pptPresentation.SaveAs(BasePath + "result\\2_example.ppt", 
         PowerPoint.PpSaveAsFileType.ppSaveAsDefault, 
         MsoTriState.msoTrue // TODO: что за параметр??? 
        ); 
pptPresentation.Close(); 

现在,我怎么能更改objTextRng字体颜色?

回答

6

下面的代码将字体颜色设置为红色:

objTextRng.Font.Color.RGB = Color.Red.ToArgb(); 

如果你想指定不同的颜色,你可以用其他的pre-defined colors之一,或使用Color.FromArgb method指定自己的RGB值。

无论哪种方式,请确保您使用Color对象上的ToArgb methodRGB属性要求指定RGB颜色值。

+1

实际上,尽管该属性的PowerPoint名称*为BGR格式的解释颜色,但它将其设置为蓝色。 将字体颜色设置为红色的最简单(也是最不优雅的)方法是指定十六进制颜色(反转R和B字节):'range.Font.Color.RGB = 0x0000FF; - 同样,蓝色将是'range.Font.Color.RGB = 0xFF0000;'等 (*:它实际上是RGB格式,但它是大端,意味着这些字节从右到左存储,而不是从左到右)。 – BrainSlugs83

0

我认为this MSDN page解释一下。

编辑: 但这只能解释如何在VBScript中做到这一点。您可以看到TextRange对象有一个属性Font。这将返回Font对象描述here这些资源显示您可以访问RGB属性。你可以像科迪告诉你的那样设置它。如果您需要更多信息,请参阅我刚刚指出的MSDN部分。

+0

您当然可以从该页面收集解释,但是它谈论的是一个DropCap而不是一个TextRange对象,并且示例代码在VB 6.0/VBScript中提供,这不易转换为C#。特别是C#中没有'RGB'函数。 –

+0

我同意,我只是不想只把链接。它有时很烦人,所以我只是复制了代码示例。 –

+0

同样,问题在于代码示例**在C#**中不起作用,因为问题被标记。没有'RGB'函数,你必须像我的回答所建议的那样(这是首选方法),或者导入'Microsoft.VisualBasic'命名空间来使用'Information.RGB'函数。 –

5

使用此为2007年PPTX

private int BGR(Color color) 
    { 
     // PowerPoint's color codes seem to be reversed (i.e., BGR) not RGB 
     //  0x0000FF produces RED not BLUE 
     //  0xFF0000 produces BLUE not RED 
     // so we have to produce the color "in reverse" 

     int iColor = color.R + 0xFF * color.G + 0xFFFF * color.B; 

     return iColor; 
    } 

例如

shape.TextFrame.TextRange.Font.Color.RGB = BGR(Color.Red); 
+1

这似乎仍然是在Powerpoint 2013中的情况(我想这是相同的格式)。有趣的是,当你将'Color.RGB'设置为红色时,你会变得没有这个功能。 :) – Raziel

0

objTextRng.Font.Color.RGB = System.Drawing.ColorTranslator.ToOl(System.Drawing.Color.Blue);