728x90
1. 강의 개요
이번 강의에서는 **사용자 정의 컨트롤(User Control)**을 제작하고, 이를 Windows Forms 애플리케이션에서 활용하는 방법을 학습합니다.
사용자 정의 컨트롤은 기본 컨트롤(Button, Label 등)을 조합하여 재사용 가능한 컴포넌트를 만드는 데 사용됩니다.
2. 학습 목표
- 사용자 정의 컨트롤을 설계 및 제작.
- 속성과 이벤트를 추가하여 사용자 정의 컨트롤의 동작 정의.
- 폼에 사용자 정의 컨트롤을 추가하고 활용.
3. 사용자 정의 컨트롤이란?
**사용자 정의 컨트롤(User Control)**은 Windows Forms의 기본 컨트롤을 조합하거나 새로운 동작을 추가하여 커스터마이징한 컨트롤입니다.
- 코드 재사용성을 높이고 유지 보수를 간소화.
- 프로젝트에 특화된 기능을 제공.
UserControl 주요 구성
구성 요소 설명
속성 | 컨트롤의 외부 동작을 제어하는 설정값. |
이벤트 | 컨트롤에서 특정 작업이 발생했을 때 알림. |
메서드 | 컨트롤의 동작 정의. |
4. 실습: 사용자 정의 컨트롤 제작
요구사항
- 사용자 정의 컨트롤을 설계하여 숫자를 입력하고 값을 증가/감소하는 기능 구현.
- 사용자 정의 속성으로 최소값, 최대값, 현재값 정의.
- 버튼 클릭 이벤트로 숫자를 증가/감소.
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
UserControl | NumericControl | (없음) | 폼 중앙 | (200 x 60) |
5. 코드 작성
1. 사용자 정의 컨트롤 파일 생성
솔루션 탐색기 > 프로젝트 우클릭 > 추가 > 새 항목 > User Control
- 파일 이름: NumericControl.cs
2. NumericControl.cs
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class NumericControl : UserControl
{
private int _currentValue = 0;
private int _minValue = 0;
private int _maxValue = 100;
public NumericControl()
{
InitializeComponent();
UpdateValueDisplay();
}
// 최소값 속성
[Category("Custom"), Description("최소값 설정")]
public int MinValue
{
get => _minValue;
set
{
_minValue = value;
if (_currentValue < _minValue)
{
_currentValue = _minValue;
UpdateValueDisplay();
}
}
}
// 최대값 속성
[Category("Custom"), Description("최대값 설정")]
public int MaxValue
{
get => _maxValue;
set
{
_maxValue = value;
if (_currentValue > _maxValue)
{
_currentValue = _maxValue;
UpdateValueDisplay();
}
}
}
// 현재값 속성
[Category("Custom"), Description("현재값 설정")]
public int CurrentValue
{
get => _currentValue;
set
{
if (value >= _minValue && value <= _maxValue)
{
_currentValue = value;
UpdateValueDisplay();
}
}
}
// 증가 버튼 클릭 이벤트
private void BtnIncrease_Click(object sender, EventArgs e)
{
if (_currentValue < _maxValue)
{
_currentValue++;
UpdateValueDisplay();
}
}
// 감소 버튼 클릭 이벤트
private void BtnDecrease_Click(object sender, EventArgs e)
{
if (_currentValue > _minValue)
{
_currentValue--;
UpdateValueDisplay();
}
}
// 값 표시 업데이트
private void UpdateValueDisplay()
{
lblValue.Text = _currentValue.ToString();
}
}
}
3. NumericControl.Designer.cs
namespace WindowsFormsApp1
{
partial class NumericControl
{
private System.ComponentModel.IContainer components = null;
private Button btnIncrease;
private Button btnDecrease;
private Label lblValue;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.btnIncrease = new Button();
this.btnDecrease = new Button();
this.lblValue = new Label();
this.SuspendLayout();
// btnIncrease
this.btnIncrease.Location = new System.Drawing.Point(140, 15);
this.btnIncrease.Name = "btnIncrease";
this.btnIncrease.Size = new System.Drawing.Size(40, 30);
this.btnIncrease.TabIndex = 0;
this.btnIncrease.Text = "+";
this.btnIncrease.UseVisualStyleBackColor = true;
this.btnIncrease.Click += new System.EventHandler(this.BtnIncrease_Click);
// btnDecrease
this.btnDecrease.Location = new System.Drawing.Point(10, 15);
this.btnDecrease.Name = "btnDecrease";
this.btnDecrease.Size = new System.Drawing.Size(40, 30);
this.btnDecrease.TabIndex = 1;
this.btnDecrease.Text = "-";
this.btnDecrease.UseVisualStyleBackColor = true;
this.btnDecrease.Click += new System.EventHandler(this.BtnDecrease_Click);
// lblValue
this.lblValue.AutoSize = true;
this.lblValue.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
this.lblValue.Location = new System.Drawing.Point(80, 18);
this.lblValue.Name = "lblValue";
this.lblValue.Size = new System.Drawing.Size(25, 28);
this.lblValue.TabIndex = 2;
this.lblValue.Text = "0";
// NumericControl
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lblValue);
this.Controls.Add(this.btnDecrease);
this.Controls.Add(this.btnIncrease);
this.Name = "NumericControl";
this.Size = new System.Drawing.Size(200, 60);
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
4. Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeCustomControl();
}
private void InitializeCustomControl()
{
// 사용자 정의 컨트롤 추가
NumericControl numericControl = new NumericControl
{
Location = new System.Drawing.Point(100, 100),
MinValue = 0,
MaxValue = 50,
CurrentValue = 10
};
this.Controls.Add(numericControl);
}
}
}
5. 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 = "사용자 정의 컨트롤 예제";
this.ResumeLayout(false);
}
}
}
6. 실행 결과
- 컨트롤 초기 상태
- 중앙에 사용자 정의 컨트롤(NumericControl)이 표시됩니다.
- 기본값: CurrentValue = 10.
- 값 증가/감소
- "+" 버튼 클릭 → 값이 1씩 증가.
- "-" 버튼 클릭 → 값이 1씩 감소.
- MinValue와 MaxValue 범위를 벗어나지 않음.
7. 주요 개념 요약
- UserControl 제작
- 속성, 이벤트를 정의하여 재사용 가능한 컨트롤 제작.
- 속성(Custom Properties)
- MinValue, MaxValue, CurrentValue와 같은 사용자 정의 속성을 통해 동작 제어.
- 폼과 연동
- 사용자 정의 컨트롤을 폼에 동적으로 추가 가능.
728x90
'Study > C#' 카테고리의 다른 글
C# Windows Forms 강의 34편: TableLayoutPanel을 활용한 유연한 레이아웃 관리 (0) | 2025.03.09 |
---|---|
C# Windows Forms 강의 33편: Panel과 ScrollBar를 활용한 스크롤 가능한 인터페이스 만들기 (0) | 2025.03.08 |
C# Windows Forms 강의 31편: ContextMenuStrip으로 동적 컨텍스트 메뉴 구현 (0) | 2025.03.06 |
C# Windows Forms 강의 30편: DataGridView 컨트롤로 데이터 관리 (0) | 2025.03.05 |
C# Windows Forms 강의 29편: OpenFileDialog와 SaveFileDialog로 파일 관리 (0) | 2025.03.04 |