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