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!

3 comments:

Anonymous said...

Hi
As you have sujjested to take separate class ImgHost.I have taken all these.But while running the application its throws me ....
*********
Exception : Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

So what can i do now to solve this issue.

mailme: das.dwipayan@gmail.com

Suman Chakrabarti said...

Sorry, you'll have to give me more detail.

If I were you, I'd look up the HRESULT on the Microsoft support site.

Suman Chakrabarti said...

This was actually written for Office 2003. You would not use this for Office 2007 as it no longer has the CommandBar, it has the IRibbon interface.