MenuItem.DrawItem 事件

定义

当菜单项的 OwnerDraw 属性设置为 true 并且发出绘制菜单项的请求时发生。

C#
public event System.Windows.Forms.DrawItemEventHandler DrawItem;

事件类型

示例

下面的代码示例演示如何处理 DrawItem 事件。 此示例使用 BrushFont绘制菜单项,然后在菜单项周围绘制 Rectangle 。 绘图通过 Graphics 对象执行,该对象将传递给 参数中的 DrawItemEventArgs 事件处理程序。 此示例要求已将项的 属性初始化 OwnerDrawtrue。 对于 C# 示例,请在 窗体的构造函数的 后面 InitializeComponent添加以下代码,以挂接 事件:

this.menuItem1.DrawItem += new DrawItemEventHandler(menuItem1_DrawItem);

C#

// The DrawItem event handler.
private void menuItem1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{

    string myCaption = "Owner Draw Item1";

    // Create a Brush and a Font with which to draw the item.
    Brush myBrush = System.Drawing.Brushes.AliceBlue;
    Font myFont = new Font(FontFamily.GenericSerif, 14, FontStyle.Underline, GraphicsUnit.Pixel);
    SizeF mySizeF = e.Graphics.MeasureString(myCaption, myFont);

    // Draw the item, and then draw a Rectangle around it.
    e.Graphics.DrawString(myCaption, myFont, myBrush, e.Bounds.X, e.Bounds.Y);
    e.Graphics.DrawRectangle(Pens.Black, new Rectangle(e.Bounds.X, e.Bounds.Y, Convert.ToInt32(mySizeF.Width), Convert.ToInt32(mySizeF.Height)));
}

注解

DrawItemEventArgs传递给DrawItem事件处理程序的参数提供了一个 Graphics 对象,使你能够在菜单项的图面上执行绘图和其他图形操作。 可以使用此事件处理程序创建满足应用程序需求的自定义菜单。 有关处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 10

另请参阅