Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

SetStyle and e.Graphics in my onPaint override just won't work together and are sending my application into an ambiguous break mode.

Here's the code:

VB
Public Class CustomProgressbar
    Inherits Control

    Private loaded As Boolean = False

    Public Sub New()
        SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint Or ControlStyles.DoubleBuffer, True)
    End Sub

    Public Sub init()
        loaded = True
    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        If Not loaded Then Return

        Using g As Graphics = e.Graphics
            '    g.FillRectangle(New LinearGradientBrush(New Rectangle(0, 0, Width + 1, Height + 1), GraphicsUtils._c(178, 178, 178), GraphicsUtils._c(140, 140, 140), 90), New Rectangle(0, 0, Width + 1, Height + 1))
            '    g.FillRectangle(New LinearGradientBrush(New Rectangle(1, 1, Width - 2, Height - 2), GraphicsUtils._c(242, 242, 242), GraphicsUtils._c(226, 226, 226), 90), New Rectangle(1, 1, Width - 2, Height - 2))

            '    If Not _v = 0 Then
            '        Dim c As Color = GraphicsUtils._c(150, 0, 255)
            '        Dim h As HslColor = HslColor.fromColor(c)

            '        g.FillRectangle(New LinearGradientBrush(New Rectangle(2, 2, _v, Height - 5), (h - New HslColor(0, 0, 0.037)).toColor(), (h - New HslColor(0, 0, 0.206)).toColor(), 90), New Rectangle(2, 2, _v, Height - 5))
            '        g.DrawLine(GraphicsUtils._p((h - New HslColor(0, 0, 0.02)).toColor()), 2, Height - 3, _v + 1, Height - 3)
            '    End If
        End Using
    End Sub


What I have tried:

If I remove the Using statement, it works fine. If I remove the SetStyle statement, it works fine too. I've tried changing the time I call init() to the load event of the form, to a button click, yet nothing works.
Posted
Updated 3-Feb-18 13:35pm
v2

1 solution

You get the graphics (e.Graphics) from the system but you're disposing it with 'Using' ('Using' disposes the object used). So, don't use 'Using' but for example:
VB
Dim g As Graphics = e.Graphics
 
Share this answer
 
Comments
[no name] 3-Feb-18 20:06pm    
Perfect, any idea why that works normally but not with SetStyle?
[no name] 3-Feb-18 20:45pm    
You should never dispose objects that you haven't created, but it does not always go wrong (immediately) as you've noticed.
In this case it goes wrong because of the use of the 'DoubleBuffer' (SetStyle) option set.
It tries to paint the control from the 'double buffer' using the graphics you have disposed.

Thanks for your answer and voting, Peter

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900