覆寫 OnPaint 方法
覆寫 .NET Framework 中定義之任何事件的基本步驟完全相同,並摘要于下列清單中。
覆寫繼承的事件
覆寫受保護的
On
EventName 方法。On
從覆寫On
的 EventName 方法呼叫基類的 EventName 方法,讓已註冊的委派接收事件。
這裡 Paint 會詳細討論此事件,因為每個 Windows Forms 控制項都必須覆寫 Paint 它繼承自 Control 的事件。 基 Control 類不知道衍生控制項需要如何繪製,而且不會在 方法中 OnPaint 提供任何繪製邏輯。 的 OnPaintControl 方法只會將事件分派 Paint 至已註冊的事件接收器。
如果您在如何:開發簡單的 Windows Forms 控制項 中 完成範例,您會看到覆寫 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 類別是 Managed 類別,可存取新的 Windows 圖形程式庫 GDI+的功能。 物件 Graphics 有繪製點、字串、線條、弧線、橢圓形和其他許多圖案的方法。
每當控制項需要變更其視覺效果顯示時,就會叫用其 OnPaint 方法。 這個方法接著會 Paint 引發 事件。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應