此处详细介绍了
Paint
事件,因为每个 Windows 窗体控件都必须重写它从
Control
继承的
Paint
事件。
Control
基类不知道需要如何绘制派生控件,并且未在
OnPaint
方法中提供任何绘制逻辑。
Control
的
OnPaint
方法只是将
Paint
事件分派给已注册的事件接收器。
如果已完成
如何:开发简单的 Windows 窗体控件
中的示例,则可看到一个重写
OnPaint
方法的示例。 以下代码片段摘自该示例。
Public Class FirstControl
Inherits Control
Public Sub New()
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
' Call the OnPaint method of the base class.
MyBase.OnPaint(e)
' Call methods of the System.Drawing.Graphics object.
e.Graphics.DrawString(Text, Font, New SolidBrush(ForeColor), RectangleF.op_Implicit(ClientRectangle))
End Sub
End Class
public class FirstControl : Control {
public FirstControl() {}
protected override void OnPaint(PaintEventArgs e) {
// Call the OnPaint method of the base class.
base.OnPaint(e);
// Call methods of the System.Drawing.Graphics object.
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle);
PaintEventArgs 类包含 Paint 事件的数据。 它具有两个属性,如以下代码所示。
Public Class PaintEventArgs
Inherits EventArgs
Public ReadOnly Property ClipRectangle() As System.Drawing.Rectangle
End Property
Public ReadOnly Property Graphics() As System.Drawing.Graphics
End Property
End Class
public class PaintEventArgs : EventArgs {
public System.Drawing.Rectangle ClipRectangle {}
public System.Drawing.Graphics Graphics {}
ClipRectangle 是要绘制的矩形,Graphics 属性引用 Graphics 对象。 System.Drawing 命名空间中的类是托管类,它们提供对新 Windows 图形库 GDI+ 的功能的访问。 Graphics 对象具有绘制点、字符串、线条、弧线、椭圆形和许多其他形状的方法。
每当控件需要更改其视觉对象显示时,该控件都会调用其 OnPaint 方法。 此方法又会引发 Paint 事件。
呈现 Windows 窗体控件