vb.net中怎样实现位图菜单?
VB.NET中,您可以通过自己绘制菜单项的方式来定制菜单。
首先,需设置该菜单项,如MenuItemExit菜单项的OwnerDraw属性为true;
然后,需要处理MenuItemExit菜单项的MeasureItem事件的响应方法Private Sub MenuItemExit_MeasureItem(ByVal sender As Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles MenuItemExit.MeasureItem和该菜单项的DrawItem事件的响应方法Private Sub MenuItemExit_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles MenuItemExit.DrawItem。
其中:
MeasureItem:用于设置菜单项的高度和宽度;
DrawItem:用来绘制实际的菜单项,包括图标,文本等等。
下面提供一段示例代码,用来实现加图标exit.bmp的菜单项MenuItemExit,可供您参考:
Private Sub MenuItemExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemExit.Click
Me.Close()
End Sub
Private Sub MenuItemExit_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles MenuItemExit.DrawItem
Dim rc As Rectangle = New Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
Dim rcf As RectangleF = New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
e.Graphics.FillRectangle(New SolidBrush(Color.White), rc)
Dim s As MenuItem = sender
Dim strItem As String = s.Text
Dim sf As StringFormat = New StringFormat()
sets text alignment information.
sf.Alignment = StringAlignment.Far
sets the line alignment.
sf.LineAlignment = StringAlignment.Center
e.Graphics.DrawString(strItem, New Font("Veranda", 10), New SolidBrush(Color.Blue), rcf, sf)
e.Graphics.DrawRectangle(New Pen(New SolidBrush(Color.White)), rc)
If (e.State = (DrawItemState.NoAccelerator Or DrawItemState.Selected)) Then
e.Graphics.FillRectangle(New SolidBrush(Color.CornflowerBlue), rc)
e.Graphics.DrawString(strItem, New Font("Veranda", 10, FontStyle.Bold Or FontStyle.Underline), New SolidBrush(Color.Yellow), rcf, sf)
e.Graphics.DrawRectangle(New Pen(New SolidBrush(Color.Blue)), rc)
Draws a focus rectangle within the bounds specified in the DrawItemEventArgs constructor.
e.DrawFocusRectangle()
End If
Dim imgExit As Image = New Bitmap("exit.bmp")
Dim sz As SizeF = imgExit.PhysicalDimension
Dim x As Single = e.Bounds.X + 5
Dim y As Single = (e.Bounds.Bottom + e.Bounds.) / 2 - sz.Height / 2
e.Graphics.DrawImage(imgExit, x, y)
End Sub
Private Sub MenuItemExit_MeasureItem(ByVal sender As Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles MenuItemExit.MeasureItem
e.ItemHeight = 25
e.ItemWidth = 75
End Sub }