[C#] 텍스트 에디터(윈도우 메모장) 만들기 7

2024. 2. 7. 19:06[C#]/[C# 윈폼] 혼자해보는 윈도우 메모장 만들기

찾기 기능을 구현하다가 생각한대로 되지 않아서 코드를 뜯어봤다.

이전 코드에서 같은 namespace에 폼을 하나 더 생성해서 코드로 구현했는데 찾아보니 폼을 여러개 만들 수 있었다.

폼 디자이너가 없다는 것이 이상해서 의문을 품고 있었는데 해결됐다.

 

1. 폼 디자인 다시 하기

2. 찾기 기능

3. 다음 찾기 & 이전 찾기

4. 바꾸기 기능을 추가해줄 것이다.


1. 폼 디자인 다시 하기

 

  • 기존에 같은 NameSpace 안에 Form Class를 직접 코드로 쳐서 제작했다.
  • 디자인을 직접 코드로 치려니 시간도 많이 걸리고 비효율적이었다.
  • 추가 -> 양식(Windows Form)을 추가해서 폼을 분리했다. 그리고 코드를 전부 수정했다.

 

줄 이동 코드 변경

 

LineMoveForm

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyTextEditor
{
    //줄 이동 폼
    public partial class LineMoveForm : Form
    {
        private RichTextBox mainTextBox;
        public LineMoveForm(RichTextBox textBox)
        {
            mainTextBox = textBox;
            InitializeComponent();
        }

        // TextBox 입력 제한 - 숫자만 입력 가능하도록
        private void TextBoxToMove_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        private void moveButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBoxToMove.Text))
            {
                int lineNumber = int.Parse(textBoxToMove.Text);
                MoveToLine(lineNumber);
            }
            else
            {
                MessageBox.Show("이동할 줄 번호를 입력하세요.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void MoveToLine(int lineNumber)
        {
            // 입력된 줄 번호가 유효한 범위인지 확인
            if (lineNumber >= 1 && lineNumber <= mainTextBox.Lines.Length)
            {
                // 해당 줄로 커서 이동
                mainTextBox.SelectionStart = mainTextBox.GetFirstCharIndexFromLine(lineNumber - 1);
                mainTextBox.ScrollToCaret();
                mainTextBox.Focus();
                this.Close(); // 이동 완료 후 폼 닫기
            }
            else
            {
                MessageBox.Show("유효하지 않은 줄 번호입니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cancleButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
// 찾기, 줄 이동 다이얼로그 호출
private void ShowDialogs(string spec)
{
   if (spec == "move")
    {
        if (moveDialog == null || moveDialog.IsDisposed)
        {
            moveDialog = new LineMoveForm(MyTextArea);
            moveDialog.Show(this);
        }
        else
        {
            moveDialog.BringToFront();
        }

    }
}

 

 

 

반응형