[英]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.