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

C# Windows Forms 강의 51편: 메모장 애플리케이션 제작

by wawManager 2025. 3. 26.

1. 강의 개요

이번 강의에서는 Windows Forms를 사용해 메모장 애플리케이션을 제작합니다.
텍스트 파일을 열고, 저장하고, 새로 만들 수 있는 간단한 텍스트 에디터를 구현하며, **메뉴 스트립(MenuStrip)**과 파일 입출력(File I/O)을 활용합니다.


2. 학습 목표

  1. MenuStrip 컨트롤을 사용해 파일 메뉴 구현.
  2. 텍스트 파일 열기, 저장, 새로 만들기 기능 구현.
  3. 텍스트 편집기를 구성하고, 사용자가 입력한 데이터를 관리.

3. 메모장 기능 요구사항

  1. 파일 메뉴
    • 새로 만들기: 텍스트 박스를 초기화.
    • 열기: OpenFileDialog를 사용해 텍스트 파일을 열고 내용 표시.
    • 저장: SaveFileDialog를 사용해 텍스트 파일 저장.
  2. 텍스트 편집
    • 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. 실행 결과

  1. 초기 상태
    • 빈 텍스트 박스와 메뉴("파일 → 새로 만들기, 열기, 저장")가 표시됩니다.
  2. 새로 만들기
    • "파일 → 새로 만들기" 클릭 → 텍스트 박스가 초기화되고, 제목이 "새 파일 - 메모장"으로 변경됩니다.
  3. 파일 열기
    • "파일 → 열기" 클릭 → OpenFileDialog가 표시되고 선택한 파일의 내용이 텍스트 박스에 로드됩니다.
  4. 파일 저장
    • "파일 → 저장" 클릭 → SaveFileDialog가 표시되며, 입력한 텍스트가 파일에 저장됩니다.

6. 주요 개념 요약

  1. MenuStrip과 ToolStripMenuItem
    • 메뉴 스트립을 사용해 파일 메뉴 구성.
  2. File I/O (파일 입출력)
    • File.ReadAllText, File.WriteAllText로 텍스트 파일 읽기/쓰기 구현.
  3. OpenFileDialog와 SaveFileDialog
    • 파일 열기 및 저장을 위한 표준 대화 상자 활용.