[英]C# converting a VBA macro to C# with custom RGB color
在将VBA宏转换为用C#编码的插件时,我遇到了以下僵局。
原始的VBA代码为:
Selection.Font.Name = "Times New Roman"
Selection.Font.Size = 14
Selection.Font.Bold = True
Selection.Font.BoldBi = True
Selection.Shading.Texture = wdTextureNone
Selection.Shading.ForegroundPatternColor = wdColorAutomatic
Selection.Shading.BackgroundPatternColor = RGB(173, 216, 230)
使用Office.Interop
命名空间转换为C#:
using Microsoft.Office;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
Word.Document oWordDoc = new Word.Document();
var Selection = oWordDoc.ActiveWindow.Selection;
Selection.Font.Name = "Times New Roman";
Selection.Font.Size = 14;
Selection.Shading.Texture = Word.WdTextureIndex.wdTextureNone;
Selection.Shading.ForegroundPatternColor = Word.WdColor.wdColorAutomatic;
Selection.Shading.BackgroundPatternColor = Word.ColorFormat.RGB(173, 216, 230);
由于RGB
不是方法,因此无法编译此代码。 我试图弄清楚如何使用可用的方法来做到这一点,但是到目前为止还没有运气。
对此,我们将提供任何建议或对转换有解释的任何描述。
更新:
实际上,它看起来像以下作品:
Color mycolor = Color.FromArgb(173, 216, 230);
Selection.Shading.BackgroundPatternColor = (Word.WdColor)(mycolor.R + 0x100 * mycolor.G + 0x10000 * mycolor.B);
这个问题使用相同的方法。 但是它看起来仍然太复杂了...
更新2:
根据以下建议,这似乎是最平滑的方法:
Selection.Shading.BackgroundPatternColor = RGB(172,216,230);
private Word.WdColor RGB(int p1, int p2, int p3)
{
return (Word.WdColor)p1 + (0x100 * p2) + (0x10000 * p3);
}
您实际上在VBA代码中调用的RGB
函数位于VBA标准库的“ Information
模块中-至少根据Rubberduck 2.0的上下文相关状态栏(免责声明:我编写了该功能):
该RGB
函数实际上只需要输入3个数字并输出相应的RGB十六进制值即可。
这个问题专门询问如何从System.Drawing.Color
转换为WdColor
值-接受的答案看起来很像您的“太复杂”代码。 另一个解决方案是导入Microsoft.VisualBasic
,并使用相同Information.RGB
功能...但我畏缩,每当我看到Microsoft.VisualBasic
在.NET项目中的任何地方进口-这恶臭的东西正在做错误的。
相反,您可以制作一个简单的扩展方法:
using System.Drawing;
using Microsoft.Interop.Word;
static class ColorExtensions
{
public static WdColor ToWdColor(this Color color)
{
return (WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B);
}
}
这将您的代码变为:
var color = Color.FromArgb(173, 216, 230).ToWdColor();
要从RGB十进制设置颜色:
Selection.Shading.BackgroundPatternColor = (Word.WdColor)(173 + 216 * 256 + 230 * 65536);
从RGB十六进制开始:
Selection.Shading.BackgroundPatternColor = (Word.WdColor)0x00E6D8AD;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.