Custom MenuItem problem when used in ContextMenu

I want to add Icons to my ContextMenu so I created the following class:
[code]
public class ImageMenuItem : MenuItem
{
private Font font;
private Icon icon;

public ImageMenuItem ( string text, Icon icon ) : base ( text )
{
// Set our icon
this.icon = icon;
// Set our text
base.Text = text;
// Set our font
this.font = SystemInformation.MenuFont;
// Owner draws
base.OwnerDraw = true;
} // End Constructor

protected new void OnMeasureItem ( MeasureItemEventArgs e )
{
// Call the base mesure item
base.OnMeasureItem ( e );
// Set our height
e.ItemHeight = ( int ) e.Graphics.MeasureString ( base.Text, this.font ).Height + 5;
// Set our width
e.ItemWidth = ( int ) e.Graphics.MeasureString ( base.Text, this.font ).Width + this.icon.Width + 5;
} // End OnMeasureItem override

protected new void OnDrawItem ( DrawItemEventArgs e )
{
// Draw the base
base.OnDrawItem ( e );

// If we have an image
if ( null != icon )
// Dtaw the image
e.Graphics.DrawIcon ( icon, e.Bounds.Left + 3, e.Bounds.Top + 2 );

// Draw the text with the supplied colors and in the set region.
e.Graphics.DrawString(this.Text, this.font, new SolidBrush ( SystemColors.WindowText ), e.Bounds.Left + icon.Width, e.Bounds.Top + 3);
} // End OnDrawItem function
} // End ImageMenuItem class
[/code]
I have been adding the a test item by doing:

[code]
contextMenu.MenuItems.Add ( new ImageMenuItem ( "test", new Icon ( Assembly.GetExecutingAssembly ( ).GetManifestResourceStream ( "TimeKeeper.Images.test.ico" ) )) );
[/code]

All I get is a blank menu item... Anyone have any ideas


Answer this question

Custom MenuItem problem when used in ContextMenu

  • OBeckles

    Hi!

    First of all if you override OnDrawItem(), then you must not add "new" modifier. You must use "override". In your sample you create two new methods OnDrawItem()/OnMeasureItem(), but not overrides.

    protected override void OnDrawItem(...)...

    If you are using .NET 2.0 - use ToolstripMenuItem - it have Font and Image already.



  • RA-SJD

    Sorry my bad.
    New was just a test.
    In the actualy code I am using override.

  • Custom MenuItem problem when used in ContextMenu