菜單|右鍵
自己做出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;
}
}
說明:這裡我沒有畫按鈕按下時的樣子(懶:),主要是以後進一步改進),當然也沒有畫表徵圖,也是為了以後改進,這隻是一個初步的形態,大家看看有什麼更高的方法?!