共用方式為


覆寫 OnPaint 方法

更新:2007 年 11 月

覆寫定義在 .NET Framework 中任何事件的基本步驟是相同的,並且摘要在下列清單中。

若要覆寫繼承的事件

  1. 覆寫受保護的 OnEventName 方法。

  2. 從覆寫的 OnEventName 方法呼叫基底類別的 OnEventName 方法,以便註冊的委派 (Delegate) 能接收事件。

Paint 事件將在這裡詳細討論,因為每一個 Windows Form 控制項都必須覆寫繼承自 ControlPaint 事件。Control 基底類別並不知如何繪製衍生控制項,而且不提供 OnPaint 方法中的任何繪製邏輯。ControlOnPaint 方法僅將 Paint 事件分派給已登錄的事件接收者。

若您是透過 HOW TO:開發簡單的 Windows Form 控制項中的範例來執行,則您已見過覆寫 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 類別,提供對 GDI+ (新的 Windows 圖庫) 功能的存取。Graphics 物件具有方法,可繪製點、字串、直線、弧形、橢圓形和許多其他形狀。

每當控制項需要變更其視覺顯示時,會叫用其 OnPaint 方法。這個方法會接著引發 Paint 事件。

請參閱

概念

呈現 Windows Form 控制項

定義 Windows Form 控制項中的事件

其他資源

處理和引發事件