Example: Setting a RibbonControl image from an embedded resource

534 views
Skip to first unread message

Gideon

unread,
Oct 28, 2010, 2:39:55 AM10/28/10
to Excel-Dna
In this example I will quickly show how to set a custom image that is
part of the "External Library" assembly embedded resources. This is
useful for people who want to control the ribbon in a compiled
assembly rather than in the .dna file.

Please note that the using the .dna file for menu items (i.e. ribbon
or command bars) is by far the easiest and simplest way of doing
things.

Assume you have an embedded image resource (m.png) in your "External
Library" assembly. To set this image on a ribbon button you need to
hook onto the getImage callback attribute for that ribbon control
which returns a IPictureDisp interface. Govert exposes the
IPictureDisp interface through ExcelDna.Integeration which helps a lot
for this example.

using...
Make sure that you have all the necessary references.

[ComVisible(true)]
public class MyRibbon : ExcelRibbon
{
public override string GetCustomUI(string uiName)
{
return
@"
<customUI xmlns='http://schemas.microsoft.com/office/2006/01/
customui'>
<ribbon>
<tabs>
<tab idMso='TabAddIns'>
<group id='group1' label='Group1'>
<button id='button1' label='Button1'
getImage='GetButtonImage' showImage='true' />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
";
}

public IPictureDisp GetThisImage(IRibbonControl control)
{
System.Drawing.Image i;
i = ClassLibrary1.Properties.Resources.m;
// or you could also do
// i = new System.Drawing.Bitmap("C:\\temp\\m.png");
return AxHostConverter.ImageToPictureDisp(i);
}

}

internal class AxHostConverter : System.Windows.Forms.AxHost
{
private AxHostConverter() : base("") { }

static public IPictureDisp ImageToPictureDisp(System.Drawing.Image
image)
{
return (IPictureDisp)GetIPictureDispFromPicture(image);
}
}

See the blog entry by Andrew Whitechapel for more info on how to
convert System.Drawing.Image to IPictureDisp.

I hope this safes someone a bit of time.

- Gideon

Govert van Drimmelen

unread,
Oct 30, 2010, 5:58:31 PM10/30/10
to Excel-Dna
Hi Gideon,

Are you sure you need the whole ImageToPictureDisp story? Your
System.Drawing.Image object is almost certainly a
System.Drawing.Bitmap already, which you can just return as is, due to
some magic .NET conversion.

Initially I also had the whole conversion story, but then I realized
it is not needed. The IPictureDisp definition is left over in Excel-
Dna by mistake....

Govert

Gideon

unread,
Oct 31, 2010, 11:00:59 AM10/31/10
to Excel-Dna
Hi Govert

You are right. Although the getImage callback signature has a return
type of IPictureDisp, you can also use Image, Bitmap, etc. It works
perfectly. Thanks for pointing that out.

Regards
- Gideon
Reply all
Reply to author
Forward
0 new messages