自己做出vs.net風格的右鍵菜單(簡單,實用)
此主題相關圖片如下:class mymenuitem : system.windows.forms.menuitem
{
public mymenuitem()
{
//這里很重要,必須把owerdraw設為true,這樣可以自己畫菜單,否則便是讓操作系統畫菜單了,默認的是false
this.ownerdraw=true;
}
protected override void ondrawitem(sysdrawitemeventargs e)
{
//要重畫菜單,是沒有onpaint方法重載的,只有重載ondrawitem方法!
graphics g=e.graphics;
g.smoothingmode=smoothingmode.antialias;//抗鋸齒
font f = new font(fontfamily.genericserif, 12, fontstyle.regular, graphicsunit.pixel);//設定菜單的字體
pen p=new pen(color.navy,1);//這是畫邊框的字體
if(e.state==drawitemstate.noaccelerator)//一開始右鍵單擊出現菜單,但是鼠標并沒有移上去
{ //用白色的底色
g.fillrectangle(brushes.whitesmoke,e.bounds.x-2,e.bounds.y-2,121,23);
}
//鼠標移上去,但是并沒有單擊
if ((e.state &drawitemstate.selected)==drawitemstate.selected)
{
//花邊框和底色
g.fillrectangle(brushes.lightsteelblue,e.bounds.x,e.bounds.y,109,20);
g.drawline(p,e.bounds.x,e.bounds.y,e.bounds.x,e.bounds.y+19);
g.drawline(p,e.bounds.x,e.bounds.y+19,e.bounds.x+109,e.bounds.y+19);
g.drawline(p,e.bounds.x+109,e.bounds.y+19,e.bounds.x+109,e.bounds.y);
g.drawline(p,e.bounds.x+109,e.bounds.y,e.bounds.x,e.bounds.y);
}
//顯示文字
g.drawstring(this.text,f,brushes.black,e.bounds.x,e.bounds.y);
g.dispose();
}
//這是很重要的,這給你的菜單定義了大小,高20,寬100,否則你的菜單什么也看不到
protected override void onmeasureitem(measureitemeventargs e)
{
e.itemheight=20;
e.itemwidth=100;
}
}
說明:這里我沒有畫按鈕按下時的樣子(懶:),主要是以后進一步改進),當然也沒有畫圖標,也是為了以后改進,這只是一個初步的形態,大家看看有什么更高的方法?!