Friday, October 14, 2005

Icons on an Office CommandBar

I've recently had a problem with loading images in Office CommandBar buttons. I found some information on the web about it, but it was neither complete or it , but I took that information further anyways.

First of all, I created a subclass called ImageHost which inherits from AxHost


private class ImageHost : System.Windows.Forms.AxHost
{
public ImageHost() : base("59EE46BA-677D-4d20-BF10-8D8067CB8B33")
{ }

/// <summary>
/// Gets a <see cref="stdole.IPictureDisp">from an input
/// <see cref="System.Drawing.Image">.
/// <summary>
public stdole.IPictureDisp GetIPictureDisp(System.Drawing.Image image)
{
return (stdole.IPictureDisp)GetIPictureDispFromPicture(image);
}

/// <summary>
/// Gets a <see cref="stdole.IPictureDisp"> from an input
/// <see cref="System.Drawing.Icon">.
/// </summary>
/// <remarks>
/// The benefit of this is when you put Icons in the Resources.resx file.
/// It's easy to just drop them in.
/// </remarks>
public stdole.IPictureDisp GetIPictureDisp(Icon icon)
{
System.IO.Stream img = new System.IO.MemoryStream();
icon.Save(img);
return GetIPictureDisp(Image.FromStream(img));
}
}


After setting this up, you must use the image host to get the stdole.IPictureDisp:


CommandBarButton button = CreateButton(
bar, "My Button",
Office.MsoButtonStyle.msoButtonIconAndCaption);
button.Picture = iconHost.GetIPictureDisp(
Properties.Resources.MyButton);


Enjoy!