Export (0) Print
Expand All

How to: Copy Pixels for Reducing Flicker in Windows Forms 

Code Example

When you animate a simple graphic, users can sometimes encounter flicker or other undesirable visual effects. One way to limit this problem is to use a "bitblt" process on the graphic. Bitblt is the "bit-block transfer" of the color data from an origin rectangle of pixels to a destination rectangle of pixels.

With Windows Forms, bitblt is accomplished using the CopyFromScreen method of the Graphics class. In the parameters of the method, you specify the source and destination (as points), the size of the area to be copied, and the graphics object used to draw the new shape.

In the example below, a shape is drawn on the form in its Paint event handler. Then, the CopyFromScreen method is used to duplicate the shape.

NoteNote

Setting the form's DoubleBuffered property to true will make graphics-based code in the Paint event be double-buffered. While this will not have any discernable performance gains when using the code below, it is something to keep in mind when working with more complex graphics-manipulation code.

Example

private void Form1_Paint(System.Object sender,
    System.Windows.Forms.PaintEventArgs e)
        {
        e.Graphics.FillEllipse(Brushes.DarkBlue, new
            Rectangle(10,10,60,60));
        e.Graphics.FillRectangle(Brushes.Khaki, new
            Rectangle(20,30,60,10));
        e.Graphics.CopyFromScreen(new Point(10, 10), new Point(100, 100), 
            new Size(70, 70));
}

Compiling the Code

The code above is run in the form's Paint event handler so that the graphics persist when the form is redrawn. As such, do not call graphics-related methods in the Load event handler, because the drawn content will not be redrawn if the form is resized or obscured by another form.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft