Double Buffering Windows Forms

As much as we would like it not to be the case, graphics can be slow enough to watch as the screen is refreshed. Our eyes, sensitive to movement and particularly to edge detection so that we don't walk off of cliffs or run into trees, often pick up the redraw cycle of computer graphics which, at best is mildly annoying or at worst can cause headaches, eyestrain and in susceptible people, even fits.

Much of this effect is caused by the sequential re-drawing of many graphical elements such as a chart with many lines or a game with many moving items. In a perfect world, the sequential redraw would be completely hidden from the user and the completed graphic presented in its entirety. This is essentially the technique used in double buffering.

Windows Forms provides an automatic method of double buffering that can be used by simply setting a few styles in your form or control. For most applications, this is enough but in certain cases, more control over the process is desirable so manually double buffering a control is also possible.

First, take a look at the standard and built in method of double buffering. This is accomplished by setting the styles:

  • ControlStyles.AllPaintingInWmPaint
  • ControlStyles.UserPaint
  • ControlStyles.DoubleBuffer

When these are all set true, the draw process is modified so that instead of your Paint handler being passed a Graphics for the screen, it is passed a Graphics for an in-memory bitmap. When you draw to this Graphics object, you are drawing on an invisible image. At the end of the draw cycle, this bitmap is copied to the main window automatically and the actual pixels you see are all changed in a fraction of a second instead of one at a time as the draw cycle progresses.

To set up automatic double buffering for a Form, you would use the following line of code in the constructor, after the InitializeComponent method call.

C#

this.SetStyle(

ControlStyles.AllPaintingInWmPaint |

ControlStyles.UserPaint |

ControlStyles.DoubleBuffer,true);

VB

me.SetStyle(

ControlStyles.AllPaintingInWmPaint OR _

ControlStyles.UserPaint OR _

ControlStyles.DoubleBuffer,true)

Manual double buffering can be useful if you don't want the system so make assumptions for you such as whether the background is opaque or transparent or perhaps if you want to create a more complex buffering system. There are a few simple rules that you need to follow to get manual double buffering right.

First, don�t create a new back-buffer every draw cycle. Only create or destroy the bitmap when the window's client size changes. Second, only create a bitmap of the size you need. Clearing pixels takes time and so if there are more pixels than you need, you're just wasting processor cycles. Lastly, use the simplest draw method to copy the bitmap to the screen. DrawImageUnscaled is the way to go here.

Before the big demo, listing 1 shows all the salient points of a manual double buffered application.

private Bitmap _backBuffer;

protected override void OnPaint(PaintEventArgs e)

{

if(_backBuffer==null)

{

_backBuffer=new Bitmap(this.ClientSize.Width,this.ClientSize.Height);

}

Graphics g=Graphics.FromImage(_backBuffer);

//Paint your graphics on g here

g.Dispose();

//Copy the back buffer to the screen

e.Graphics.DrawImageUnscaled(_backBuffer,0,0);

//base.OnPaint (e); //optional but not recommended

}

protected override void OnPaintBackground(PaintEventArgs pevent)

{

//Don't allow the background to paint

}

protected override void OnSizeChanged(EventArgs e)

{

if(_backBuffer!=null)

{

_backBuffer.Dispose();

_backBuffer=null;

}

base.OnSizeChanged (e);

}

VB

Private _backBuffer As Bitmap

Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)

If _backBuffer Is Nothing Then

_backBuffer = New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height)

End If

Dim g As Graphics = Graphics.FromImage(_backBuffer)

'Paint on the Graphics object here

g.Dispose()

'Copy the back buffer to the screen

e.Graphics.DrawImageUnscaled(_backBuffer, 0, 0)

End Sub 'OnPaint

'base.OnPaint (e); //optional but not recommended

Protected Overrides Sub OnPaintBackground(ByVal pevent As PaintEventArgs)

End Sub 'OnPaintBackground

'Don't allow the background to paint

Protected Overrides Sub OnSizeChanged(ByVal e As EventArgs)

If Not (_backBuffer Is Nothing) Then

_backBuffer.Dispose()

_backBuffer = Nothing

End If

MyBase.OnSizeChanged(e)

End Sub 'OnSizeChanged

The following listing shows a practical double buffered application. A checkbox enables you to choose whether double buffering is used or if the graphics are drawn directly to the screen for the sake of comparison.

C#

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace DoubleBuffer

{

/// <summary>

/// Summary description for Form1.

/// </summary>

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.Timer timer1;

private System.ComponentModel.IContainer components;

private System.Windows.Forms.CheckBox checkBox1;

float _angle;

bool _doBuffer;

public Form1()

{

//

// Required for Windows Form Designer support

//

InitializeComponent();

//

// TODO: Add any constructor code after InitializeComponent call

//

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.components = new System.ComponentModel.Container();

this.timer1 = new System.Windows.Forms.Timer(this.components);

this.checkBox1 = new System.Windows.Forms.CheckBox();

this.SuspendLayout();

//

// timer1

//

this.timer1.Enabled = true;

this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

//

// checkBox1

//

this.checkBox1.Location = new System.Drawing.Point(8, 8);

this.checkBox1.Name = "checkBox1";

this.checkBox1.TabIndex = 0;

this.checkBox1.Text = "Double Buffer";

this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);

//

// Form1

//

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

this.ClientSize = new System.Drawing.Size(292, 273);

this.Controls.Add(this.checkBox1);

this.Name = "Form1";

this.Text = "Form1";

this.ResumeLayout(false);

}

#endregion

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void timer1_Tick(object sender, System.EventArgs e)

{

_angle+=3;

if(_angle>359)

_angle=0;

Invalidate();

}

private Bitmap _backBuffer;

protected override void OnPaint(PaintEventArgs e)

{

if(_backBuffer==null)

{

_backBuffer=new Bitmap(this.ClientSize.Width,this.ClientSize.Height);

}

Graphics g=null;

if(_doBuffer)

g=Graphics.FromImage(_backBuffer);

else

g=e.Graphics;

g.Clear(Color.White);

g.SmoothingMode=SmoothingMode.AntiAlias;

Matrix mx=new Matrix();

mx.Rotate(_angle,MatrixOrder.Append);

mx.Translate(this.ClientSize.Width/2,this.ClientSize.Height/2,MatrixOrder.Append);

g.Transform=mx;

g.FillRectangle(Brushes.Red,-100,-100,200,200);

mx=new Matrix();

mx.Rotate(-_angle,MatrixOrder.Append);

mx.Translate(this.ClientSize.Width/2,this.ClientSize.Height/2,MatrixOrder.Append);

g.Transform=mx;

g.FillRectangle(Brushes.Green,-75,-75,149,149);

mx=new Matrix();

mx.Rotate(_angle*2,MatrixOrder.Append);

mx.Translate(this.ClientSize.Width/2,this.ClientSize.Height/2,MatrixOrder.Append);

g.Transform=mx;

g.FillRectangle(Brushes.Blue,-50,-50,100,100);

if(_doBuffer)

{

g.Dispose();

//Copy the back buffer to the screen

e.Graphics.DrawImageUnscaled(_backBuffer,0,0);

}

//base.OnPaint (e); //optional but not recommended

}

protected override void OnPaintBackground(PaintEventArgs pevent)

{

//Don't allow the background to paint

}

protected override void OnSizeChanged(EventArgs e)

{

if(_backBuffer!=null)

{

_backBuffer.Dispose();

_backBuffer=null;

}

base.OnSizeChanged (e);

}

private void checkBox1_CheckedChanged(object sender, System.EventArgs e)

{

_doBuffer=this.checkBox1.Checked;

}

}

}

VB

Imports System

Imports System.Drawing

Imports System.Drawing.Drawing2D

Imports System.Collections

Imports System.ComponentModel

Imports System.Windows.Forms

Imports System.Data

Namespace DoubleBuffer

'/ <summary>

'/ Summary description for Form1.

'/ </summary>

Public Class Form1

Inherits System.Windows.Forms.Form

Private WithEvents timer1 As System.Windows.Forms.Timer

Private components As System.ComponentModel.IContainer

Private WithEvents checkBox1 As System.Windows.Forms.CheckBox

Private _angle As Single

Private _doBuffer As Boolean

Public Sub New()

'

' Required for Windows Form Designer support

'

InitializeComponent()

End Sub 'New

'

' TODO: Add any constructor code after InitializeComponent call

'

'/ <summary>

'/ Clean up any resources being used.

'/ </summary>

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub 'Dispose

#Region "Windows Form Designer generated code"

'/ <summary>

'/ Required method for Designer support - do not modify

'/ the contents of this method with the code editor.

'/ </summary>

Private Sub InitializeComponent()

Me.components = New System.ComponentModel.Container

Me.timer1 = New System.Windows.Forms.Timer(Me.components)

Me.checkBox1 = New System.Windows.Forms.CheckBox

Me.SuspendLayout()

'

' timer1

'

Me.timer1.Enabled = True

'

' checkBox1

'

Me.checkBox1.Location = New System.Drawing.Point(8, 8)

Me.checkBox1.Name = "checkBox1"

Me.checkBox1.TabIndex = 0

Me.checkBox1.Text = "Double Buffer"

'

' Form1

'

Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

Me.ClientSize = New System.Drawing.Size(292, 273)

Me.Controls.Add(checkBox1)

Me.Name = "Form1"

Me.Text = "Form1"

Me.ResumeLayout(False)

End Sub 'InitializeComponent

#End Region

'/ <summary>

'/ The main entry point for the application.

'/ </summary>

<STAThread()> _

Shared Sub Main()

Application.Run(New Form1)

End Sub 'Main

Private Sub timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)Handles timer1.Tick

_angle += 3

If _angle > 359 Then

_angle = 0

End If

Invalidate()

End Sub 'timer1_Tick

Private _backBuffer As Bitmap

Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)

If _backBuffer Is Nothing Then

_backBuffer = New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height)

End If

Dim g As Graphics = Nothing

If _doBuffer Then

g = Graphics.FromImage(_backBuffer)

Else

g = e.Graphics

End If

g.Clear(Color.White)

g.SmoothingMode = SmoothingMode.AntiAlias

Dim mx As New Matrix

mx.Rotate(_angle, MatrixOrder.Append)

mx.Translate(Me.ClientSize.Width / 2, Me.ClientSize.Height / 2, MatrixOrder.Append)

g.Transform = mx

g.FillRectangle(Brushes.Red, -100, -100, 200, 200)

mx = New Matrix

mx.Rotate(-_angle, MatrixOrder.Append)

mx.Translate(Me.ClientSize.Width / 2, Me.ClientSize.Height / 2, MatrixOrder.Append)

g.Transform = mx

g.FillRectangle(Brushes.Green, -75, -75, 149, 149)

mx = New Matrix

mx.Rotate(_angle * 2, MatrixOrder.Append)

mx.Translate(Me.ClientSize.Width / 2, Me.ClientSize.Height / 2, MatrixOrder.Append)

g.Transform = mx

g.FillRectangle(Brushes.Blue, -50, -50, 100, 100)

If _doBuffer Then

g.Dispose()

'Copy the back buffer to the screen

e.Graphics.DrawImageUnscaled(_backBuffer, 0, 0)

End If

End Sub 'OnPaint

'base.OnPaint (e); //optional but not recommended

Protected Overrides Sub OnPaintBackground(ByVal pevent As PaintEventArgs)

End Sub 'OnPaintBackground

'Don't allow the background to paint

Protected Overrides Sub OnSizeChanged(ByVal e As EventArgs)

If Not (_backBuffer Is Nothing) Then

_backBuffer.Dispose()

_backBuffer = Nothing

End If

MyBase.OnSizeChanged(e)

End Sub 'OnSizeChanged

Private Sub checkBox1_CheckedChanged(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles checkBox1.CheckedChanged

_doBuffer = Me.checkBox1.Checked

End Sub 'checkBox1_CheckedChanged

End Class 'Form1

End Namespace 'DoubleBuffer

When running the program looks like this�

Figure 1: Double buffering in action.

原地址:

http://bobpowell.net/doublebuffer.aspx

Double Buffering Windows Forms的更多相关文章

  1. .net chart(图表)控件的使用-System.Windows.Forms.DataVisualization.dll

    这个案例指在介绍微软这套免费又功能强大的图表控件Microsoft Chart Controls for Microsoft .NET Framework 3.5,通过它,可让您的项目及报表,轻松套用 ...

  2. create Context Menu in Windows Forms application using C# z

    In this article let us see how to create Context Menu in Windows Forms application using C# Introduc ...

  3. DotNetBar For Windows Forms 12.5.0.2 官方原版及注册

    转自原文DotNetBar For Windows Forms 12.5.0.2 官方原版及注册 DotNetBar是一款带有56个 Windows Form 控件的工具箱,使开发人员可以轻而易举地创 ...

  4. C#Windows Forms 计算器--xdd

    一.计算器 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data ...

  5. Wizard Framework:一个自己开发的基于Windows Forms的向导开发框架

    最近因项目需要,我自己设计开发了一个基于Windows Forms的向导开发框架,目前我已经将其开源,并发布了一个NuGet安装包.比较囧的一件事是,当我发布了NuGet安装包以后,发现原来已经有一个 ...

  6. windows forms 上一个类似于wpf snoop 的工具: Hawkeye

    windows forms 上一个类似于wpf snoop 的工具: Hawkeye 周银辉 WPF上有snoop这样的run time object editor让人用着很爽, 今天搜到了一个for ...

  7. WPF中实例化Com组件,调用组件的方法时报System.Windows.Forms.AxHost+InvalidActiveXStateException的异常

    WPF中实例化Com组件,调用组件的方法时报System.Windows.Forms.AxHost+InvalidActiveXStateException的异常 在wpf中封装Com组件时,调用组件 ...

  8. DotNetBar for Windows Forms 12.9.0.0_冰河之刃重打包版及制作Visual Studio C#项目模板文件详解

    关于 DotNetBar for Windows Forms 12.9.0.0_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...

  9. DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版------------- ...

随机推荐

  1. 2016HUAS暑假集训训练2 D - 敌兵布阵

    Description Lily 特别喜欢养花,但是由于她的花特别多,所以照料这些花就变得不太容易.她把她的花依次排成一行,每盆花都有一个美观值.如果Lily把某盆花照料的好的话,这盆花的美观值就会上 ...

  2. 关于使用MVVM模式在WPF的DataGrid控件中实现ComboBox编辑列

    最近在做一个组态软件的项目,有一个需求需要在建立IO设备变量的时候选择变量的类型等. 建立IO变量的界面是一个DataGrid实现的,可以一行一行的新建变量,如下如所示: 这里需要使用带有ComboB ...

  3. Bootstrap (导航、标签、面包屑导航)

    导航 Bootstrap中可用的导航有相似的标记,用基类.nav开头,这是相似的部分.改变修饰类可以改变样式. <!DOCTYPE html> <html> <head& ...

  4. 利用.htaccess实现伪静态方法

    首先配置服务器启动重写模块打开 Apache 的配置文件 httpd.conf .将#LoadModule rewrite_module modules/mod_rewrite前面的#去掉.保存后重启 ...

  5. matlab函数bwareaopen的详解

    matlab函数_连通区域 1. matlab函数bwareaopen──删除小面积对象格式:BW2 = bwareaopen(BW,P,conn)作用:删除二值图像BW中面积小于P的对象,默认情况下 ...

  6. Android课程---视图组件之开关按钮

    <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="ht ...

  7. 【iCore3 双核心板_FPGA】例程十三:FSMC总线通信实验——复用地址模式

    实验指导书及代码包下载: http://pan.baidu.com/s/1nuYpI8x iCore3 购买链接: https://item.taobao.com/item.htm?id=524229 ...

  8. C# mvc中为Controller或Action添加定制特性实现登录验证

    在本文开始前,先简单讲两个知识点: 1.每个action执行前都会先执行OnActionExecuting方法: 2.FCL提供了多种方式来检测特性的存在,比如IsDefined.GetCustomA ...

  9. php连接和操作mysql数据库

    <?php //数据库连接文件:link.php $link = mysql_connect("localhost", "root", "&qu ...

  10. iOS小技巧3

    将颜色合成图片 将颜色合成图片 +(UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1 ...