Memory leak with ownerdraw menu

  • Thread starter Thread starter Claes Bergefall
  • Start date Start date
C

Claes Bergefall

I started playing around with ownerdrawn menuitems
in a contextmenu and found a serious problem

At first they work just fine, but after a while I get
an OutOfMemoryException and they stop working.
And it's not just my application that stops working,
the whole OS breaks!! No other menu (in any program)
works correctly anymore

The only way to get it to work again is to reboot the
computer!!

I found this thread that talks about the problem (long URL):
http://groups.google.com/groups?hl=...5%24129b7550%249ae62ecf%40tkmsftngxa02&rnum=1

In it a guy from MS admits that there is a problem, but I haven't
found a solution or workaround anywhere

As mentioned in the thread the breakdown can be triggered
faster by doing something that throws an exception
(division by 0 in this case) inside DrawItem.

Does anybody have any idea what's happening and/or how
to solve it? As far as I can see I dispose everything that should
be disposed (see code below)

I'm using vesion 1.1 on Windows 2000

Here's the code:

Private Sub MenuItem_MeasureItem( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MeasureItemEventArgs)

Dim mnu As MenuItem = CType(sender, MenuItem)
Dim textFormat As New StringFormat(StringFormatFlags.NoWrap)
textFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show
e.ItemHeight = SystemInformation.MenuFont.Height +
SystemInformation.Border3DSize.Height * 2
If e.ItemHeight < 16 Then
e.ItemHeight = 16
End If
e.ItemWidth = CInt(e.Graphics.MeasureString(" " & mnu.Text,
SystemInformation.MenuFont, -1, textFormat).Width) + 16
textFormat.Dispose()

End Sub

Private Sub MenuItem_DrawItem( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.DrawItemEventArgs)

Dim mnu As MenuItem = CType(sender, MenuItem)
Dim foreBrush As New SolidBrush(e.ForeColor)
Dim textFormat As New StringFormat(StringFormatFlags.NoWrap)
Dim textRect As RectangleF = RectangleF.FromLTRB(e.Bounds.Left + 16,
e.Bounds.Top, e.Bounds.Right, e.Bounds.Bottom)
Dim x As Single = (CSng(e.Bounds.Height) - 4) / 2
Dim imageRect As RectangleF = RectangleF.FromLTRB(e.Bounds.Left + 6,
e.Bounds.Top + x, e.Bounds.Left + 10, e.Bounds.Bottom - x)
textFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show
textFormat.LineAlignment = StringAlignment.Center

e.DrawBackground()
e.Graphics.FillEllipse(foreBrush, imageRect)
e.Graphics.DrawString(" " & mnu.Text, SystemInformation.MenuFont,
foreBrush, textRect, textFormat)
If e.State = DrawItemState.Focus Then
e.DrawFocusRectangle()
End If
foreBrush.Dispose()
textFormat.Dispose()

End Sub


/claes
 
Back
Top