Share via


기존 컨트롤 확장

기존 컨트롤에 기능을 더 추가하려는 경우 기존 컨트롤에서 상속되는 컨트롤을 만들 수 있습니다. 새 컨트롤은 기본 컨트롤의 모든 기능과 시각적 측면을 포함하지만 확장할 수 있는 기회를 제공합니다. 예를 들어, Button을 상속하는 컨트롤을 만든 경우 새 컨트롤은 단추처럼 보이고 작동합니다. 컨트롤의 동작을 사용자 지정하는 새 메서드와 속성을 만들 수 있습니다. 일부 컨트롤을 사용하면 OnPaint 메서드를 재정의하여 컨트롤의 모양을 변경할 수 있습니다.

프로젝트에 사용자 지정 컨트롤 추가

새 프로젝트를 만든 후 Visual Studio 템플릿을 사용하여 사용자 정의 컨트롤을 만듭니다. 다음 단계에서는 프로젝트에 사용자 정의 컨트롤을 추가하는 방법을 보여 줍니다.

  1. Visual Studio에서 프로젝트 탐색기 창을 찾습니다. 그런 다음, 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가>클래스를 선택합니다.

    Visual Studio 솔루션 탐색기를 마우스 오른쪽 단추로 클릭하여 Windows Forms 프로젝트에 사용자 정의 컨트롤 추가

  2. 이름 상자에 사용자 정의 컨트롤의 이름을 입력합니다. Visual Studio에서는 사용할 수 있는 기본 이름과 고유 이름을 제공합니다. 그런 다음 추가를 누릅니다.

    Windows Forms용 Visual Studio의 항목 추가 대화 상자

사용자 정의 컨트롤이 만들어지면 Visual Studio에서 컨트롤에 대한 코드 편집기를 엽니다. 다음 단계는 이 사용자 지정 컨트롤을 단추로 전환하고 확장하는 것입니다.

사용자 지정 컨트롤을 단추로 변경

이 섹션에서는 사용자 지정 컨트롤을 클릭 횟수를 계산하고 표시하는 단추로 변경하는 방법을 알아봅니다.

.NET용 Windows Forms 사용자 지정 컨트롤

프로젝트에 CustomControl1이라는 사용자 지정 컨트롤을 추가하면 컨트롤 디자이너가 열립니다. 열리지 않는 경우 솔루션 탐색기에서 컨트롤을 두 번 클릭합니다. 사용자 지정 컨트롤을 Button에서 상속하고 확장하는 컨트롤로 변환하려면 다음 단계를 수행합니다.

  1. 컨트롤 디자이너를 연 상태에서 F7을 누르거나 디자이너 창을 마우스 오른쪽 단추로 클릭하고 코드 보기를 선택합니다.

  2. 코드 편집기에서 클래스 정의가 표시됩니다.

    namespace CustomControlProject
    {
        public partial class CustomControl2 : Control
        {
            public CustomControl2()
            {
                InitializeComponent();
            }
    
            protected override void OnPaint(PaintEventArgs pe)
            {
                base.OnPaint(pe);
            }
        }
    }
    
    Public Class CustomControl2
    
        Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
            MyBase.OnPaint(e)
    
            'Add your custom paint code here
        End Sub
    
    End Class
    
  3. 먼저 _counter라는 클래스 범위 변수를 추가합니다.

    private int _counter = 0;
    
    Private _counter As Integer = 0
    
  4. OnPaint 메서드를 재정의합니다. 이 메서드는 컨트롤을 그립니다. 컨트롤은 단추 위에 문자열을 그려야 하므로 먼저 기본 클래스의 OnPaint 메서드를 호출한 다음 문자열을 그려야 합니다.

    protected override void OnPaint(PaintEventArgs pe)
    {
        // Draw the control
        base.OnPaint(pe);
    
        // Paint our string on top of it
        pe.Graphics.DrawString($"Clicked {_counter} times", Font, Brushes.Purple, new PointF(3, 3));
    }
    
    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    
        ' Draw the control
        MyBase.OnPaint(e)
    
        ' Paint our string on top of it
        e.Graphics.DrawString($"Clicked {_counter} times", Font, Brushes.Purple, New PointF(3, 3))
    
    End Sub
    
  5. 마지막으로 OnClick 메서드를 재정의합니다. 이 메서드는 컨트롤을 누를 때마다 호출됩니다. 코드는 카운터를 늘인 다음 컨트롤 자체를 다시 그리도록 하는 Invalidate 메서드를 호출합니다.

    protected override void OnClick(EventArgs e)
    {
        // Increase the counter and redraw the control
        _counter++;
        Invalidate();
    
        // Call the base method to invoke the Click event
        base.OnClick(e);
    }
    
    Protected Overrides Sub OnClick(e As EventArgs)
    
        ' Increase the counter and redraw the control
        _counter += 1
        Invalidate()
    
        ' Call the base method to invoke the Click event
        MyBase.OnClick(e)
    
    End Sub
    

    최종 코드는 다음 코드 조각과 같습니다.

    public partial class CustomControl1 : Button
    {
        private int _counter = 0;
    
        public CustomControl1()
        {
            InitializeComponent();
        }
    
        protected override void OnPaint(PaintEventArgs pe)
        {
            // Draw the control
            base.OnPaint(pe);
    
            // Paint our string on top of it
            pe.Graphics.DrawString($"Clicked {_counter} times", Font, Brushes.Purple, new PointF(3, 3));
        }
    
        protected override void OnClick(EventArgs e)
        {
            // Increase the counter and redraw the control
            _counter++;
            Invalidate();
    
            // Call the base method to invoke the Click event
            base.OnClick(e);
        }
    }
    
    Public Class CustomControl1
    
        Private _counter As Integer = 0
    
        Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    
            ' Draw the control
            MyBase.OnPaint(e)
    
            ' Paint our string on top of it
            e.Graphics.DrawString($"Clicked {_counter} times", Font, Brushes.Purple, New PointF(3, 3))
    
        End Sub
    
        Protected Overrides Sub OnClick(e As EventArgs)
    
            ' Increase the counter and redraw the control
            _counter += 1
            Invalidate()
    
            ' Call the base method to invoke the Click event
            MyBase.OnClick(e)
    
        End Sub
    
    End Class
    

이제 컨트롤이 만들어졌으므로 프로젝트를 컴파일하여 도구 상자 창을 새 컨트롤로 채웁니다. 양식 디자이너를 열고 컨트롤을 양식으로 끌어옵니다. 프로젝트를 실행하고 단추를 클릭하면 클릭 수를 계산하고 단추 위에 텍스트를 그립니다.

사용자 지정 컨트롤을 보여 주는 Windows Forms용 Visual Studio 도구 상자 창.