본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 41편: Custom Control 제작

by wawManager 2025. 3. 16.

1. 강의 개요

이번 강의에서는 **Custom Control(사용자 정의 컨트롤)**을 제작하는 방법을 학습합니다.
Custom Control은 기본 컨트롤(Button, Label 등)을 조합하거나, 새로운 동작을 추가하여 재사용 가능한 컴포넌트를 만드는 데 사용됩니다.


2. 학습 목표

  1. Custom Control의 개념과 필요성을 이해.
  2. 사용자 정의 속성 및 이벤트를 가진 컨트롤 제작.
  3. 폼에 Custom Control을 추가하고 활용.

3. Custom Control이란?

Custom Control은 Windows Forms의 기본 컨트롤을 상속받아 기능을 확장하거나 새로운 컨트롤을 제작하는 기능입니다.

  • 재사용성 증가: 여러 폼에서 공통 기능을 사용 가능.
  • 확장성: 기본 컨트롤의 동작을 수정하거나 새로운 동작 추가.
  • 유지보수 편리: 코드 중복을 줄이고 중앙에서 관리.

4. 실습: 간단한 Custom Control 제작

요구사항

  1. 버튼과 텍스트박스를 포함하는 사용자 정의 컨트롤 제작.
  2. 버튼 클릭 시 텍스트박스에 미리 정의된 메시지를 표시.
  3. 외부에서 메시지를 설정할 수 있는 속성 추가.

Custom Control 제작

1. Custom Control 생성

  1. 솔루션 탐색기 > 프로젝트 우클릭 > 추가 > 새 항목 > User Control
  2. 파일 이름: MyCustomControl.cs

2. 코드 작성

MyCustomControl.cs

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class MyCustomControl : UserControl
    {
        // 메시지 속성
        private string _message = "안녕하세요!";

        [Category("Custom Properties")]
        [Description("버튼 클릭 시 텍스트박스에 표시될 메시지")]
        public string Message
        {
            get => _message;
            set => _message = value;
        }

        public MyCustomControl()
        {
            InitializeComponent();
        }

        // 버튼 클릭 이벤트
        private void BtnShowMessage_Click(object sender, EventArgs e)
        {
            txtMessage.Text = _message;
        }
    }
}

MyCustomControl.Designer.cs

namespace WindowsFormsApp1
{
    partial class MyCustomControl
    {
        private System.ComponentModel.IContainer components = null;
        private Button btnShowMessage;
        private TextBox txtMessage;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.btnShowMessage = new Button();
            this.txtMessage = new TextBox();
            this.SuspendLayout();

            // btnShowMessage
            this.btnShowMessage.Location = new System.Drawing.Point(10, 10);
            this.btnShowMessage.Name = "btnShowMessage";
            this.btnShowMessage.Size = new System.Drawing.Size(100, 30);
            this.btnShowMessage.TabIndex = 0;
            this.btnShowMessage.Text = "메시지 표시";
            this.btnShowMessage.UseVisualStyleBackColor = true;
            this.btnShowMessage.Click += new System.EventHandler(this.BtnShowMessage_Click);

            // txtMessage
            this.txtMessage.Location = new System.Drawing.Point(120, 10);
            this.txtMessage.Name = "txtMessage";
            this.txtMessage.Size = new System.Drawing.Size(200, 27);
            this.txtMessage.TabIndex = 1;

            // MyCustomControl
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.txtMessage);
            this.Controls.Add(this.btnShowMessage);
            this.Name = "MyCustomControl";
            this.Size = new System.Drawing.Size(350, 50);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
}

5. Custom Control 사용

1. 폼에 Custom Control 추가

  1. Form1 디자인 화면으로 이동.
  2. **툴박스(Toolbox)**에서 MyCustomControl을 드래그하여 폼에 추가.

2. Form1.cs

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeCustomControl();
        }

        private void InitializeCustomControl()
        {
            // MyCustomControl 설정
            var customControl = new MyCustomControl
            {
                Location = new System.Drawing.Point(20, 20),
                Message = "환영합니다! C# Custom Control 예제입니다."
            };

            this.Controls.Add(customControl);
        }
    }
}

3. Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(400, 300);
            this.Name = "Form1";
            this.Text = "Custom Control 예제";
            this.ResumeLayout(false);
        }
    }
}

6. 실행 결과

  1. 폼에 Custom Control 표시
    • 버튼과 텍스트박스가 포함된 MyCustomControl이 폼에 표시됩니다.
  2. 메시지 표시
    • "메시지 표시" 버튼 클릭 → 텍스트박스에 Message 속성에 설정된 메시지가 표시됩니다.
  3. 외부에서 메시지 설정
    • customControl.Message 속성을 변경하여 버튼 클릭 시 다른 메시지를 표시할 수 있습니다.

7. 주요 개념 요약

  1. Custom Control 제작
    • UserControl을 상속받아 사용자 정의 컨트롤 제작.
    • 속성 및 이벤트를 추가하여 기능 확장.
  2. 재사용 가능한 컨트롤
    • 프로젝트 내 다른 폼에서도 쉽게 재사용 가능.
  3. 디자인 타임 속성 설정
    • [Category]와 [Description] 특성을 사용하여 디자인 타임 속성 사용자화.