OnPaint 메서드 재정의

.NET Framework에 정의된 이벤트를 재정의하기 위한 기본 단계는 동일하며 다음 목록에 요약되어 있습니다.

상속된 이벤트를 재정의하려면

  1. 보호된 OnEventName 메서드를 재정의합니다.

  2. 재정의된 OnEventName 메서드에서 기본 클래스의 OnEventName 메서드를 호출하여 등록된 대리자가 이벤트를 받도록 합니다.

모든 Windows Forms 컨트롤은 Control에서 상속하는 Paint 이벤트를 재정의해야 하기 때문에 Paint 이벤트에 대해 여기서 자세히 설명합니다. 기본 Control 클래스는 파생된 컨트롤을 어떻게 그려야 하는지 모르고 OnPaint 메서드에 그리기 논리를 제공하지 않습니다. ControlOnPaint 메서드는 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 네임스페이스의 클래스는 새 Windows 그래픽 라이브러리인 GDI+ 기능에 대한 액세스를 제공하는 관리형 클래스입니다. Graphics 개체에는 점, 문자열, 선, 호, 타원 및 기타 여러 도형을 그리는 메서드가 있습니다.

컨트롤은 시각적 표시를 변경해야 할 때마다 OnPaint 메서드를 호출합니다. 이 메서드는 Paint 이벤트를 발생시킵니다.

참조