by
Roland Schumacher alias GENiALi
14. August 2008 -- 218
words -- 1 mal gelesen
Ich glaube jeder ist mit mir einig, wenn ich sage, dass hier sieht hässlich aus.
Mit VSTO ist es jetzt aber gar nicht mal so einfach transparente Icon’s zu bekommen.
Ein Icon wird einem CommandBarButton (cbc) wie folgt hinzugefügt.
if (item.Icon.Length > 0)
{
stdole.IPictureDisp pic = GetImage(item.Icon);
if (pic != null)
{
cbc.Picture = pic;
}
} GetImage sieht so aus.
private stdole.IPictureDisp GetImage(string imageName)
{
stdole.IPictureDisp pic = null;
string file = Path.Combine(iconPath, imageName);
if (File.Exists(file))
{
try
{
pic = PictureConverter.
ImageToPictureDisp(Image.FromFile(file));
}
catch (Exception ex)
{
//Hier Fehler
}
}
return pic;
}Und der
PictureConverter ist eine eigene Klasse. Findet man überall im Inet.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace LAG.WordPlus.OfficeAddIns.Word2003
{
public class PictureConverter : AxHost
{
public PictureConverter() : base(string.Empty)
{
}
public static stdole.IPictureDisp ImageToPictureDisp(Image image)
{
return (stdole.IPictureDisp)GetIPictureDispFromPicture(image);
}
public static stdole.IPictureDisp IconToPictureDisp(Icon icon)
{
return ImageToPictureDisp(icon.ToBitmap());
}
public static Image PictureDispToImage(stdole.IPictureDisp picture)
{
return GetPictureFromIPicture(picture);
}
}
}Wie macht man nun die Icon’s transparent?
Man erweitere das erste Codesnippet um die Zeile 7.
if (item.Icon.Length > 0)
{
stdole.IPictureDisp pic = GetImage(item.Icon);
if (pic != null)
{
cbc.Picture = pic;
SetImage(cbc, item.Icon);
}
}Der Code für
SetImage sieht so aus.
private void SetImage(CommandBarButton button, string icon)
{
try
{
Bitmap bmp = new Bitmap(Path.Combine(iconPath, icon));
IntPtr Hicon = bmp.GetHicon();
Icon newIcon = Icon.FromHandle(Hicon);
ImageList newImageList = new ImageList();
newImageList.ColorDepth = ColorDepth.Depth8Bit;
newImageList.ImageSize = new Size(16, 16);
newImageList.Images.Add(newIcon);
button.Picture = PictureConverter.
ImageToPictureDisp(newImageList.Images[0]);
Bitmap mask = (Bitmap)newImageList.Images[0].Clone();
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 16; y++)
{
mask.SetPixel(x, y, (mask.GetPixel(x, y)
== Color.Transparent
|| mask.GetPixel(x, y).Name == "0")
? Color.White : Color.Black);
}
}
button.Mask = PictureConverter.ImageToPictureDisp(mask);
}
catch (Exception ex)
{
//Fehlerbehandlung
}
}
Das Ergebnis sieht dann so aus.
Viel besser. Oder?