🔎 유용한 정보
1. 강의 개요
이번 강의에서는 Windows Forms를 사용해 메모장 애플리케이션을 제작합니다.
텍스트 파일을 열고, 저장하고, 새로 만들 수 있는 간단한 텍스트 에디터를 구현하며, **메뉴 스트립(MenuStrip)**과 파일 입출력(File I/O)을 활용합니다.
2. 학습 목표
- MenuStrip 컨트롤을 사용해 파일 메뉴 구현.
- 텍스트 파일 열기, 저장, 새로 만들기 기능 구현.
- 텍스트 편집기를 구성하고, 사용자가 입력한 데이터를 관리.
3. 메모장 기능 요구사항
- 파일 메뉴
- 새로 만들기: 텍스트 박스를 초기화.
- 열기: OpenFileDialog를 사용해 텍스트 파일을 열고 내용 표시.
- 저장: SaveFileDialog를 사용해 텍스트 파일 저장.
- 텍스트 편집
- TextBox를 사용해 사용자 입력 처리.
- Multiline, Scrollbars, WordWrap 기능 지원.
4. 실습: 메모장 애플리케이션 구현
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
MenuStrip | menuStrip1 | (없음) | 상단 | (자동 크기 조정) |
ToolStripMenuItem | fileMenu | "파일" | 메뉴 스트립에 추가 | (없음) |
ToolStripMenuItem | newMenuItem | "새로 만들기" | 파일 메뉴에 추가 | (없음) |
ToolStripMenuItem | openMenuItem | "열기" | 파일 메뉴에 추가 | (없음) |
ToolStripMenuItem | saveMenuItem | "저장" | 파일 메뉴에 추가 | (없음) |
TextBox | txtEditor | (없음) | 중앙 | (400 x 300) |
코드 작성
1. Form1.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private string currentFilePath = string.Empty; // 현재 열려 있는 파일 경로
public Form1()
{
InitializeComponent();
InitializeEvents();
}
private void InitializeEvents()
{
newMenuItem.Click += NewMenuItem_Click;
openMenuItem.Click += OpenMenuItem_Click;
saveMenuItem.Click += SaveMenuItem_Click;
}
// "새로 만들기" 메뉴 클릭 이벤트
private void NewMenuItem_Click(object sender, EventArgs e)
{
txtEditor.Clear();
currentFilePath = string.Empty;
this.Text = "새 파일 - 메모장";
}
// "열기" 메뉴 클릭 이벤트
private void OpenMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
openFileDialog.Title = "파일 열기";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
currentFilePath = openFileDialog.FileName;
txtEditor.Text = File.ReadAllText(currentFilePath);
this.Text = $"{Path.GetFileName(currentFilePath)} - 메모장";
}
}
}
// "저장" 메뉴 클릭 이벤트
private void SaveMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(currentFilePath))
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
saveFileDialog.Title = "파일 저장";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
currentFilePath = saveFileDialog.FileName;
File.WriteAllText(currentFilePath, txtEditor.Text);
this.Text = $"{Path.GetFileName(currentFilePath)} - 메모장";
}
}
}
else
{
File.WriteAllText(currentFilePath, txtEditor.Text);
this.Text = $"{Path.GetFileName(currentFilePath)} - 메모장";
}
MessageBox.Show("파일이 저장되었습니다.", "저장 완료");
}
}
}
2. Form1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileMenu;
private ToolStripMenuItem newMenuItem;
private ToolStripMenuItem openMenuItem;
private ToolStripMenuItem saveMenuItem;
private TextBox txtEditor;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.menuStrip1 = new MenuStrip();
this.fileMenu = new ToolStripMenuItem();
this.newMenuItem = new ToolStripMenuItem();
this.openMenuItem = new ToolStripMenuItem();
this.saveMenuItem = new ToolStripMenuItem();
this.txtEditor = new TextBox();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
// menuStrip1
this.menuStrip1.Items.AddRange(new ToolStripItem[] { this.fileMenu });
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(400, 24);
this.menuStrip1.TabIndex = 0;
// fileMenu
this.fileMenu.DropDownItems.AddRange(new ToolStripItem[] {
this.newMenuItem,
this.openMenuItem,
this.saveMenuItem
});
this.fileMenu.Name = "fileMenu";
this.fileMenu.Text = "파일";
// newMenuItem
this.newMenuItem.Name = "newMenuItem";
this.newMenuItem.Text = "새로 만들기";
// openMenuItem
this.openMenuItem.Name = "openMenuItem";
this.openMenuItem.Text = "열기";
// saveMenuItem
this.saveMenuItem.Name = "saveMenuItem";
this.saveMenuItem.Text = "저장";
// txtEditor
this.txtEditor.Location = new System.Drawing.Point(10, 30);
this.txtEditor.Multiline = true;
this.txtEditor.ScrollBars = ScrollBars.Vertical;
this.txtEditor.Size = new System.Drawing.Size(380, 300);
this.txtEditor.TabIndex = 1;
// Form1
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(400, 350);
this.Controls.Add(this.txtEditor);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "메모장";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
5. 실행 결과
- 초기 상태
- 빈 텍스트 박스와 메뉴("파일 → 새로 만들기, 열기, 저장")가 표시됩니다.
- 새로 만들기
- "파일 → 새로 만들기" 클릭 → 텍스트 박스가 초기화되고, 제목이 "새 파일 - 메모장"으로 변경됩니다.
- 파일 열기
- "파일 → 열기" 클릭 → OpenFileDialog가 표시되고 선택한 파일의 내용이 텍스트 박스에 로드됩니다.
- 파일 저장
- "파일 → 저장" 클릭 → SaveFileDialog가 표시되며, 입력한 텍스트가 파일에 저장됩니다.
6. 주요 개념 요약
- MenuStrip과 ToolStripMenuItem
- 메뉴 스트립을 사용해 파일 메뉴 구성.
- File I/O (파일 입출력)
- File.ReadAllText, File.WriteAllText로 텍스트 파일 읽기/쓰기 구현.
- OpenFileDialog와 SaveFileDialog
- 파일 열기 및 저장을 위한 표준 대화 상자 활용.
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 53편: 간단한 음악 플레이어 구현 (0) | 2025.03.28 |
---|---|
C# Windows Forms 강의 52편: To-Do List 애플리케이션 제작 (0) | 2025.03.27 |
C# Windows Forms 강의 50편: 다중 쓰레드와 ProgressBar 활용 (0) | 2025.03.25 |
C# Windows Forms 강의 49편: 데이터 바인딩과 DataGridView 고급 사용 (0) | 2025.03.24 |
C# Windows Forms 강의 48편: 리소스 관리 (이미지, 아이콘, 사운드 파일) (0) | 2025.03.23 |
🔎 유용한 정보