BLOG.CSHARPHELPER.COM: Make an owner-drawn menu in in C#
Make an owner-drawn menu in in C#
At design time, set the menu item's OwnerDraw property to True. Then at run time, you must respond to two events for the menu: MeasureItem and DrawItem.
The MeasureItem event handler receives as a parameter an object of type MeasureItemEventArgs. The code must set this object's ItemHeight and ItemWidth properties to tell Visual Basic how much room the menu item needs. This example determines how big the string it will draw is going to be and requests enough room for the string.
// Tell Windows how big to make the menu item. private void mnuFileSayHi_MeasureItem(object sender, MeasureItemEventArgs e) { // Create the font we will use to draw the text. using (Font menu_font = new Font( FONT_NAME, FONT_SIZE, FONT_STYLE)) { // See how big the text will be. SizeF text_size = e.Graphics.MeasureString(MENU_CAPTION, menu_font);
// Set the necessary size. e.ItemHeight = (int)text_size.Height; e.ItemWidth = (int)text_size.Width; } }
The DrawItem event handler receives as a parameter an object of type DrawItemEventArgs that has properties and methods that tell where the menu should draw. This example checks the object's State parameter to see if the mouse is over the menu item. If it is, the program draws a gradient background and the menu's text in AliceBlue. If the mouse is not over the menu item, the program draws a simple light gray background with black text.
// Draw the menu item. private void mnuFileSayHi_DrawItem(object sender, DrawItemEventArgs e) { // Create the font we will use to draw the text. using (Font menu_font = new Font( FONT_NAME, FONT_SIZE, FONT_STYLE)) { // See if the mouse is over the menu item. if ((e.State & DrawItemState.Selected) != DrawItemState.None) { // The mouse is over the item. // Draw a shaded background. using (Brush menu_brush = new LinearGradientBrush( e.Bounds, Color.Red,Color.Black,90)) { e.Graphics.FillRectangle(menu_brush, e.Bounds); }
// Draw the text. e.Graphics.DrawString(MENU_CAPTION, menu_font, System.Drawing.Brushes.AliceBlue, e.Bounds.X, e.Bounds.Y); } else { // The mouse is not over the item. // Erase the background. e.Graphics.FillRectangle( System.Drawing.Brushes.LightGray, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
Comments