728x90
화면에 패널, 버튼, 라벨을 동적으로 생성한다.
using System;
using System.Windows.Forms;
namespace PanelButtonApp
{
public class MainForm : Form
{
private int panelCount; // 패널의 개수
public MainForm(int panelCount)
{
this.panelCount = panelCount;
// 폼 크기 설정
this.Width = 800;
this.Height = 600;
this.Resize += MainForm_Resize; // 폼 크기 변경 시 이벤트 핸들러 추가
// 초기 패널 배치 설정
SetupPanels();
}
private void SetupPanels()
{
// 폼의 클라이언트 영역 크기 계산
int formWidth = this.ClientSize.Width;
int formHeight = this.ClientSize.Height;
// 패널을 배치할 행과 열 계산
int panelRows = (int)Math.Ceiling(panelCount / 4.0); // 4열씩 배치한다고 가정
int panelCols = Math.Min(panelCount, 4); // 최대 4열로 제한
// 패널 크기 및 간격 계산
int panelWidth = formWidth / panelCols;
int panelHeight = formHeight / panelRows;
// 패널 생성 및 폼에 추가
for (int i = 0; i < panelCount; i++)
{
// 패널 생성
Panel panel = new Panel();
panel.Width = panelWidth;
panel.Height = panelHeight;
// 패널 위치 설정
int row = i / panelCols;
int col = i % panelCols;
panel.Left = (panelWidth) * col;
panel.Top = (panelHeight) * row;
// 순번 라벨 추가
Label label = new Label();
label.Text = $"Panel {i + 1}"; // 패널 순번 라벨
label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
label.Dock = DockStyle.Top;
label.Height = 30; // 라벨 높이
panel.Controls.Add(label);
// 패널 안에 5x5 버튼 배열 생성
CreateButtonsInPanel(panel);
// 패널 폼에 추가
this.Controls.Add(panel);
}
}
private void CreateButtonsInPanel(Panel panel)
{
panel.Controls.Clear(); // 기존 버튼 및 라벨 제거 (추가된 컨트롤 제거 방지 필요)
foreach (Control control in panel.Controls)
{
if (control is Label) // 라벨은 유지
continue;
}
int buttonSize = Math.Min(panel.Width / 5, panel.Height / 5) - 5; // 패널 크기에 맞춘 버튼 크기 계산
int margin = 5; // 버튼 간격
// 5x5 버튼 생성
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
Button button = new Button();
button.Width = buttonSize - margin;
button.Height = buttonSize - margin;
// 버튼 위치 설정
button.Left = col * buttonSize;
button.Top = row * buttonSize + 30; // 라벨 하단에 버튼 배치
// 버튼 텍스트 설정 (예: "1", "2" ...)
button.Text = (row * 5 + col + 1).ToString();
// 패널에 버튼 추가
panel.Controls.Add(button);
}
}
}
private void MainForm_Resize(object sender, EventArgs e)
{
// 폼 크기 변경 시 패널 재배치
SetupPanels();
}
[STAThread]
static void Main(string[] args)
{
int panelCount = 7; // 예시로 7개의 패널 생성
if (args.Length > 0 && int.TryParse(args[0], out int userPanelCount))
{
panelCount = userPanelCount; // 사용자 입력에 따라 패널 개수 설정
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(panelCount));
}
}
}
728x90
'C#' 카테고리의 다른 글
C# 콤보박스에 값 넣기 001 ~ 999 (0) | 2024.12.02 |
---|---|
C# DataTable 원하는 값 찾기 (0) | 2024.08.26 |
C# DataTable - 삽입, 복제 등등의 응용 방법 (0) | 2024.01.25 |
C# DataTable 사용법 - 컬럼생성, 데이터 삽입, 데이터 조회 (0) | 2024.01.25 |
C# .NET 사용자 정의 컨트롤 만들기 (1) | 2024.01.25 |