Question

I'm trying to implement a smooth-moving turning dial. I took some code for an analog clock control and I'm trying to modify it. My problem is that the graphics flicker a lot (the moving dial). I have a timer calling Form.Refresh every 10 ms. Anything faster and it flickers too much, anything slower and it stutters. This is the rest of the code:

private void InitializeComponent()
    {
        ...
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.AnalogClock_Paint);
    }

    private void AnalogClock_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
        double ms = ( DateTime.UtcNow-_startTime).TotalMilliseconds;
        double fRadHr=(ms/CYCLE_MS) *2*PI;
        e.Graphics.FillEllipse(new SolidBrush(Color.White), fCenterX - fCenterCircleRadius / 2, fCenterY - fCenterCircleRadius / 2, fCenterCircleRadius, fCenterCircleRadius);
        DrawPolygon(this.fHourThickness, this.fHourLength, hrColor, fRadHr, e);
        e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    }

    private void DrawPolygon(float fThickness, float fLength, Color color, double fRadians, System.Windows.Forms.PaintEventArgs e)
    {

        PointF A=new PointF( (float)(fCenterX+ fThickness*2*System.Math.Sin(fRadians+PI/2)), 
            (float)(fCenterY - fThickness*2*System.Math.Cos(fRadians+PI/2)) );
        PointF B=new PointF( (float)(fCenterX+ fThickness*2*System.Math.Sin(fRadians-PI/2)),
            (float)(fCenterY - fThickness*2*System.Math.Cos(fRadians-PI/2)) );
        PointF C=new PointF( (float)(fCenterX+ fLength*System.Math.Sin(fRadians)), 
            (float) (fCenterY - fLength*System.Math.Cos(fRadians)) );
        PointF D=new PointF( (float)(fCenterX- fThickness*4*System.Math.Sin(fRadians)), 
            (float)(fCenterY + fThickness*4*System.Math.Cos(fRadians) ));
        PointF[] points={A,D,B,C};
        e.Graphics.FillPolygon( new SolidBrush(color), points );
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // draws background once so at least that doesn't flicker
    }
Was it helpful?

Solution

I'm posting LarsTech's comment as an answer:

Set the DoubleBuffer property of Form to be true in the constructor.

This greatly reduced flickering.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top