1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Reflection;
using System.Resources;
using System.Windows.Forms;
public class MenuItemWithIcon : MenuItem
{
//les champs pour Icon et Font
private Icon icone;
private Font f;
//...
//le constructeur avec Icon
public MenuItemWithIcon(string texte, Icon icone, EventHandler onClick, Shortcut shortcut) : base(texte, onClick, shortcut )
{
//très important
this.OwnerDraw = true;
//une valeur par defaut du Font
this.f = new Font( "Arial", 8 );
this.icone = icone;
}
//...
// les accesseurs pour Icon et Font
public Font Font
{
get { return this.f; }
set { this.f= value; }
}
public Icon Icon
{
get { return this.icone; }
set { this.icone = value; }
}
//...
//une petite méthode pour determiner le texte complet qui s'affiche
private string GetFulltext()
{
string texte = this.Text;
// En fonction du raccourci à afficher
if ( this.ShowShortcut && (this.Shortcut != Shortcut.None) )
{
Keys k = (Keys) this.Shortcut;
TypeConverter t = TypeDescriptor.GetConverter(typeof(Keys))
texte += "\t" + t.ConvertToString(k);
}
return texte;
}
//...
//surcharge OnMeasureItem lorsque le Menu aura besoin
//de connaître la taille du menuitem avant de le dessiner
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
base.OnMeasureItem(e);
//determiner un format à adopter
StringFormat sf = new StringFormat();
sf.HotkeyPrefix = HotkeyPrefix.Show;
sf.SetTabStops(60, new float[] {0});
//recuperer le texte complet
string texte = this.GetFulltext()
//determiner la taille de l'item
SizeF s = (int) e.Graphics.MeasureString(texte, this.f, 10000, sf)
e.ItemHeight = s.Height + 10;
e.ItemWidth = s.Width + 10;
sf.Dispose();
sf = null;
}
//...
//surcharge OnDrawItem lorsque le Menu
//demande à dessiner le menuitem
{
base.OnDrawItem(e);
Brush b;
Rectangle r = e.Bounds;
// si icone
if (this.icone != null )
{e.Graphics.DrawIcon(this.icone, r.Left + 2, r.Top + 2 );
r.X += 24;
if ((e.State & DrawItemState.Selected) != 0)
{
// si selectionné
b = new LinearGradientBrush( r, SystemColors.Highlight, SystemColors.Control, 0f );
}
else
{br = SystemBrushes.Control;}
//dessiner menutem
e.Graphics.FillRectangle(b, r);
//dessiner la chaine de caractère
StringFormat sf = new StringFormat();
sf.HotkeyPrefix = HotkeyPrefix.Show;
sf.SetTabStops(60, new float[] {0});
string texte = this.GetFulltext()
b = new SolidBrush(e.ForeColor);
e.Graphics.DrawString(texte, this.f, b, r.Left + 25, r.Top + 2, sf);
b.Dispose();
b = null;
sf.Dispose();
sf = null;
}
} |
Partager