Текстовый редактор на c windows form

Рассмотрим пример проектирования стандартного оконного приложения. Простейшая последовательность действий:
1) визуальное проектирование интерфейса (перенос на форму с Панели элементов необходимых визуальных и не визуальных элементов);
2) генерация заготовок методов обработки событий, связанных с элементами управления;
3) программирование методов обработки событий.

Постановка задачи

Создать текстовый редактор с обязательными функциями работы с файлами  «Открыть» и «Сохранить как», а также функциями редактирования текста. Выбор действий с файлами осуществлять через главное меню.

Реализация

Разместим на форме визуальный элемент textBox1 класса TextBox. Размер элемента сделайте чуть меньше размера формы, сместив его вниз от заголовка на 30-40 пикселей. Задайте свойство textBox1.MultiLine = true (для редактирования текста в несколько строк).

Перетащите с Панели элементов компонент menuStrip1 класса MenuStrip для создания меню.В левом верхнем углу рабочей области формы появится кнопка «Введите здесь» , а на панели невизульных компонентов отобразится элемент menuStrip1.

Для выбора имен файлов для их чтения и записи перетащим на эту же панель элементы openFileDialog1 (класс OpenFileDialog) и saveFileDialog1 (класс SaveFileDialog).

Кликнув по кнопке «Введите здесь», введите имя раздела меню «Файл» и добавьте ниже следующие пункты меню работы с файлами «Открыть», «Сохранить как» и «Выход». Ваша форма (вместе с панелью невизуальных элементов) будет выглядеть примерно так:
Примечание: для наглядности изменено свойство формы BackColor = Color.Peru. Первая группа действий закончена.

Вторая группа действий обеспечивает генерацию  заголовков методов обработки событий, связанных к кнопками меню. Для этого дважды нажмите каждую из трех позиций меню, а также событию Load формы Form1 на закладке «События» панели «Свойства» поставьте в соответствие метод Form1_Load (двойной клик справа от в строке Load).

Откроем форму в режиме Кода (файл Form1.cs):

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

namespace ТекстовыйРедактор
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

      private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
      {

      }

      private void сохранитьКакToolStripMenuItem_Click(object sender,      EventArgs e)
      {

      }

      private void выходToolStripMenuItem_Click(object sender, EventArgs e)
      {

      }

      private void Form1_Load(object sender, EventArgs e)
      {

      }
   }
}

Перейдем к третьей группе действий — написанию кода для этих четырех методов.

Метод Form1_Load( ) используем для очистки поля компонента textBox1, для задания форматов файловых диалогов и имени файла — контрольного примера при его открытии:

private void Form1_Load(object sender, EventArgs e)
{
   textBox1.Clear();
   openFileDialog1.FileName = @"data\Text2.txt";
   openFileDialog1.Filter =
            "Текстовые файлы (*.txt)|*.txt|All files (*.*)|*.*";
   saveFileDialog1.Filter =
            "Текстовые файлы (*.txt)|*.txt|All files (*.*)|*.*";
}

Комментарий. При загрузке формы мы задаем свойство FileName объекта openFileDialog1 указанием имени файла для открытия, а также задаем фильтры для диалогов открытия и сохранения файлов.  Сравните работу программы без использования этого метода.

В методе  открытьToolStripMenuItem_Click( ) используется  компонент openFileDialog1 для выбора имени файла для чтения. Если имя не выбрано (FileName = String.Empty), то работа метода завершается. Иначе создается новый экземпляр класса System.IO.StreamReader (var Читатель) с указанием имени файла и кодировки, данные из текстового файла переносятся в textBox1, объект Читатель закрывается. Добавлена обработка исключений,  которые могут возникнуть при открытии файла:

private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
{
   openFileDialog1.ShowDialog();
   if (openFileDialog1.FileName == String.Empty) return;
   // Чтение текстового файла
   try
   {
      var Читатель = new System.IO.StreamReader(
      openFileDialog1.FileName, Encoding.GetEncoding(1251));
      textBox1.Text = Читатель.ReadToEnd();
      Читатель.Close();
   }
   catch (System.IO.FileNotFoundException Ситуация)
   {
      MessageBox.Show(Ситуация.Message + "\nНет такого файла",
               "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
   }
   catch (Exception Ситуация)
   { // отчет о других ошибках
      MessageBox.Show(Ситуация.Message,
           "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
   }
}

Аналогично выполняется запись (сохранение) текстового файла:

private void сохранитьКакToolStripMenuItem_Click(object sender,EventArgs e)
{
   saveFileDialog1.FileName = openFileDialog1.FileName;
   if (saveFileDialog1.ShowDialog() == DialogResult.OK)
   {
      try
      {
         var Писатель = new System.IO.StreamWriter(
         saveFileDialog1.FileName, false,              
                             System.Text.Encoding.GetEncoding(1251));
         Писатель.Write(textBox1.Text);
         Писатель.Close(); 
     }
     catch (Exception Ситуация)
     { // отчет о других ошибках
          MessageBox.Show(Ситуация.Message,
              "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
  }
}

Последний метод — закрытие формы — реализуется одним оператором:

private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
   this.Close();
}

Подготовим в блокноте текстовый файл Text2.txt и разместим его в подкаталоге data папки, где будет размещено ваше приложение.  Запустим программу на выполнение.   Добавьте в окне редактора несколько строк, сохраните файл с другим именем. Откройте новый файл и удалите часть текста в окне редактора.

Заметим, что работают стандартные операции выделения текста, копирования, вставки и удаления части текста с использованием мыши и комбинаций управляющих клавиш, используемых в известных текстовых редакторах.

ВЫВОД: В первом приближении поставленная задача решена. Данный пример приведен всего лишь для понимания:
во-первых,  алгоритма действий разработчика визуального приложения  «интерфейс, события-методы, реализация»;
во-вторых, удобства использования готовых компонентов (нам не пришлось программировать операции редактирования текста — стандартные события уже привязаны к компоненту textBox1);
в-третьих, целесообразности использования готовых компонентов (файловых диалогов) с точки зрения стандартизации интерфейса пользователя и программы.

 
Напомним, что в статье про классы мы отмечали, что в языке C# предусмотрено несколько разновидностей данных-членов и функций-членов. Пока мы подробно рассмотрели только поля и константы — как данные-члены, а также методы — как функции-члены класса. В следующих статьях мы рассмотрим события, как данные-члены класса и трехзвенную цепочку события-делегаты-методы. После чего вернемся к член-функциям класса: свойствам, конструкторам, финализаторам, операциям и индексаторам.


NEW: Наш Чат, в котором вы можете обсудить любые вопросы, идеи, поделиться опытом или связаться с администраторами.


Помощь проекту:

A to Z Full Forms and Acronyms

This article shows how you can build your own Notepad in Visual studio Using WinForms.

Making Notepad in Windows Forms:

Step 1: Open Visual Studio and Create a new project( Windows Form Application). Give it a Suitable name(Here we have named it as “NotePad1”).

Step 2: Click on the Create button. You will come across a Form as given below:

Step 3: Change the name of the form from its properties. This will be displayed on the top of the Notepad as its heading.

From Toolbox, select menu strip and place it on the top in the form area. In MenuStrip, you can provide the names of the various options that you want in your notepad. We are adding File, Edit, and Format options in the menu. You can add more as per your choice.
Step 4:  Now in the options provided in the MenuBar, we need to have a dialog box that will open up as the user clicks on the File, Edit, or Font option. Therefore, we will provide further options for them.

Step 5: Now we need to add a RichTextBox control from the toolbox in the form so that the user may enter input in that field. Here, we are not adding a simple textbox because it can basically take single line input whereas RichTextBox provides more control over styling the text.

Step 6: Now We need to Provide functionality to the various options in the dialog box. For options like Save, Open, Font, and Color, we need some special controls from the toolbox.

  • For save: We need to add saveFileDialog control from the toolbox.
  • For open: We need to add openFileDialog control from the toolbox.
  • For font: We need to add fontDialog control from the toolbox.
  • For Color: We need to add colorDialog control from the toolbox.

 

  • The functionality to each option can be specified in the coding section that you will come across as you double click each option.

The code for the whole notepad is given below:

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;
using System.IO;                        
// assembly for file handling//

namespace NotePad1
{

    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

// to open a new file //

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

// to open a file//

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog()== DialogResult.OK)
            {
                richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
            }
        }

// to save a file //

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.DefaultExt = ".txt";
            saveFileDialog1.Filter = "Text File|*.txt|PDF file|*.pdf|Word File|*.doc";
            DialogResult dr = saveFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
            }
        }

// to exit and close notepad//

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

// to perform undo operation on the text//

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }

// to perform redo operation//

        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }

// to cut some data from the textbox //

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

// to copy some data in the textbox //

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

// to paste some copied data//

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

// to select all the text in the text field //

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectAll();
        }

// to display date and time //

        private void dateTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = System.DateTime.Now.ToString();
        }

// for font options //

        private void fontToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (fontDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Font = fontDialog1.Font;
            }
        }

  // for providing color to the text //

        private void colorToolStripMenuItem_Click(object sender, EventArgs e)        {
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.ForeColor = colorDialog1.Color;
            }
        }
    }
}

Your own notepad is ready:

A to Z Full Forms and Acronyms

Text Editor — Windows Forms

This application is a text editor written in C# and Windows Forms as part of my college class final project in Fall 2016. Other projects
for the final project included:

  • Simple login program using a SQL local database with Visual Studio.
    Link to source: https://github.com/hjohnson12/LoginPanel
  • Simple implementation of a file watcher program that watches a source directory for changes and copies the changes to the destination directory.
    Link to source: https://github.com/hjohnson12/FileSync
  • Basic application that connects to a ftp server and does simple operations such as read contents in a directory, upload a file, and delete a file.
    Link to source: https://github.com/hjohnson12/FtpConnect

NOTE: This version is not currently being worked on, waiting on XAML Islands release for further update

  • This project was re-made into a Windows 10 Universal Windows Platform application a couple years ago when testing with UWP for the first time. It is now being re-made to use the newer framework and controls when free time is available: https://github.com/hjohnson12/NotepadEditorUWP

Screenshots of WinForms Version

Standard design for text editor:

Image of Program

Able to open files and display them into the editor:
  • Line/Column numbers also show according to where your cursor is selected

Image of Program

Able to see an example of the color before you choose it:

Image of Program

  • Uses a KnownColor object for the selected color. Once backcolor is set, it converts the color to RGB values and
    determines if its considered a lighter or darker color. It then changes the text color accordingly:

    • The following is the C# snippet:
    // fill colors in color drop down list
              foreach (System.Reflection.PropertyInfo prop in typeof(Color).GetProperties())
              {
                  if (prop.PropertyType.FullName == "System.Drawing.Color")
                  {
                      colorList.Add(prop.Name);     
                  }
              }
             
              // fill the drop down items list
              foreach(string color in colorList)
              {
                  colorStripDropDownButton.DropDownItems.Add(color);
              }
    
              // fill BackColor for each color in the DropDownItems list
              for (int i = 0; i < colorStripDropDownButton.DropDownItems.Count; i++)
              {
                  // Create KnownColor object
                  KnownColor selectedColor;
                  selectedColor = (KnownColor)System.Enum.Parse(typeof(KnownColor), colorList[i]);    // parse to a KnownColor
                  colorStripDropDownButton.DropDownItems[i].BackColor = Color.FromKnownColor(selectedColor);    // set the BackColor to its appropriate list item
    
                  // Set the text color depending on if the barkground is darker or lighter
                  // create Color object
                  Color col = Color.FromName(colorList[i]);
    
                  // 255,255,255 = White and 0,0,0 = Black
                  // Max sum of RGB values is 765 -> (255 + 255 + 255)
                  // Middle sum of RGB values is 382 -> (765/2)
                  // Color is considered darker if its <= 382
                  // Color is considered lighter if its > 382
                  sumRGB = ConvertToRGB(col);    // get the color objects sum of the RGB value
                  if (sumRGB <= MIDDLE)    // Darker Background
                  {
                      colorStripDropDownButton.DropDownItems[i].ForeColor = Color.White;    // set to White text
                  }
                  else if (sumRGB > MIDDLE)    // Lighter Background
                  {
                      colorStripDropDownButton.DropDownItems[i].ForeColor = Color.Black;    // set to Black text
                  }
              }
Icons on each menu item in the menu bar:

Image of Program

Prerequisites

Requires Visual Studio 2017 or higher to run.

Built With

  • C# Windows Forms

Contributing

[Coming Soon]

Authors

  • HunterInitial work — hjohnson012

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License — see the LICENSE.md file for details

Пришло время научить наш блокнот работать с текстом, а именно: вставлять, удалять, вырезать, копировать, искать и заменять текст. Помимо этого мы научим строку состояния выводить нам актуальную информацию о количестве символов в тексте (с пробелами и без), а также о количестве строк в документе.

Для начала напишем код для элементов меню «Правка».

Отменить

notebox.Undo();

Вырезать

if (notebox.SelectionLength > 0)
{
    notebox.Cut();
}

Копировать

if (notebox.SelectionLength > 0)
{
    notebox.Copy();
}

Вставить

notebox.Paste();

Удалить

if (notebox.SelectionLength > 0)
{
    notebox.SelectedText = «»;
}

Выделить всё

notebox.SelectAll();

Время и дата

notebox.AppendText(Environment.NewLine + Convert.ToString(System.DateTime.Now));

Найти и заменить

SearchForm findText = new SearchForm();
findText.Owner = this;
findText.Show();

Перейти…

GoToForm gotoform = new GoToForm();
gotoform.Owner = this;
gotoform.tbLineNum.Minimum = 0;
gotoform.tbLineNum.Maximum = notebox.Lines.Count();
gotoform.ShowDialog();

TextWork.cs

Теперь создадим класс TextWork.cs. В этот класс мы поместим методы поиска и замены для нашего текстового редактора, а также методы подсчета символов, строк и слов для строки состояния, метод для активации некоторых пунктов меню «Правка» только при наличии текста.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace NewNoteBlock
{
    public static class TextWork
    {
        // Метод поиска текста в TextBox
        // Для использования создаем в форме поиска глобальную переменную 
        // типа int = 0 для стартовой позиции поиска,
        // передаем в метод ссылки на TextBox’ы с исходным и искомым текстами,
        // а также необходимо указать, учитывать ли регистр букв при поиске (True — учитывать, False — не учитывать)
        public static int FindTextBox(ref TextBox textBox, string findText, ref int findCutLength, bool register)
        {
            // Поиск с учетом регистра
            if (register == true)
            {
                if (textBox.Text.Contains(findText))
                {
                    // Заносим текст в переменную string, удаляем из него уже пройденный 
                    // текст (findCutLength) в переменной nextText
                    string text = textBox.Text;
                    string nextText = text.Remove(0, findCutLength);
                    // Ищем в nextText
                    int resultPosition = nextText.IndexOf(findText);
                    // Если искомое выражение найдено — выделяем его, добавляем его позицию и длину 
                    // к значению пройденного текста (findCutLenght)
                    if (resultPosition != -1)
                    {
                        textBox.Select(resultPosition + findCutLength, findText.Length);
                        textBox.ScrollToCaret();
                        textBox.Focus();
                        findCutLength += findText.Length + resultPosition;
                    }
                    // Если попытка поиска не первая, и больше совпадений в тексте нет — обнуляем
                    // значение пройденного текста и начинаем поиск сначала
                    else if (resultPosition == -1 && findCutLength != 0)
                    {
                        findCutLength = 0;
                        return FindTextBox(ref textBox, findText, ref findCutLength, register);
                    }
                }
                else
                {
                    findCutLength = 0;
                    MessageBox.Show(«По вашему запросу ничего не нашлось.», «Совпадений не найдено», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            // Поиск без учета регистра
            else if (register == false)
            {
                if (textBox.Text.ToLower().Contains(findText.ToLower()))
                {
                    string text = textBox.Text.ToLower();
                    string nextText = text.Remove(0, findCutLength);
                    int resultPosition = nextText.IndexOf(findText.ToLower());


                    if (resultPosition != -1)
                    {
                        textBox.Select(resultPosition + findCutLength, findText.Length);
                        textBox.ScrollToCaret();
                        textBox.Focus();
                        findCutLength += findText.Length + resultPosition;
                    }
                    else if (resultPosition == -1 && findCutLength != 0)
                    {
                        findCutLength = 0;
                        return FindTextBox(ref textBox, findText, ref findCutLength, register);
                    }
                }
                // Если текст изначально не содержит результатов поиска — обнуляем findCutLength, выводим сообщение
                else
                {
                    findCutLength = 0;
                    MessageBox.Show(«По вашему запросу ничего не нашлось.», «Совпадений не найдено», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            
            return 0;
        }


        // Метод «Заменить»
        public static int ReplaceTextBox(ref TextBox textBox, string findText, string replaceText, ref int findCutLength, bool register)
        {
            if (register == true)
            {
                if (textBox.Text.Contains(findText))
                {
                    if (textBox.SelectedText == «» || textBox.SelectedText != findText)
                    {
                        string text = textBox.Text;
                        string nextText = text.Remove(0, findCutLength);
                        int resultPosition = nextText.IndexOf(findText);
                        if (resultPosition != -1)
                        {
                            textBox.Select(resultPosition + findCutLength, findText.Length);
                            textBox.ScrollToCaret();
                            textBox.Focus();
                            findCutLength += findText.Length + resultPosition;
                        }
                        else if (resultPosition == -1 && findCutLength != 0)
                        {
                            findCutLength = 0;
                            return ReplaceTextBox(ref textBox, findText, replaceText, ref findCutLength, register);
                        }
                    }
                    else if (textBox.SelectedText == findText)
                    {
                        textBox.SelectedText = replaceText;
                    }
                }
                else
                {
                    findCutLength = 0;
                    MessageBox.Show(«По вашему запросу ничего не нашлось.», «Совпадений не найдено», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else if (register == false)
            {
                if (textBox.Text.ToLower().Contains(findText.ToLower()))
                {
                    if (textBox.SelectedText == «» || textBox.SelectedText.ToLower() != findText.ToLower())
                    {
                        string text = textBox.Text.ToLower();
                        string nextText = text.Remove(0, findCutLength);
                        int resultPosition = nextText.IndexOf(findText.ToLower());
                        if (resultPosition != -1)
                        {
                            textBox.Select(resultPosition + findCutLength, findText.Length);
                            textBox.ScrollToCaret();
                            textBox.Focus();
                            findCutLength += findText.Length + resultPosition;
                        }
                        else if (resultPosition == -1 && findCutLength != 0)
                        {
                            findCutLength = 0;
                            return ReplaceTextBox(ref textBox, findText, replaceText, ref findCutLength, register);
                        }
                    }
                    else if (textBox.SelectedText.ToLower() == findText.ToLower())
                    {
                        textBox.SelectedText = replaceText;
                    }
                }
                else
                {
                    findCutLength = 0;
                    MessageBox.Show(«По вашему запросу ничего не нашлось.», «Совпадений не найдено», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return 0;
        }


        // Метод «Заменить всё»
        public static int ReplaceAllTextBox(ref TextBox textBox, string findText, string replaceText, bool register)
        {
            if (register == true)
            {
                string text = textBox.Text;
                string words = findText;
                if (textBox.Text.Contains(words))
                {
                    int startPosition = text.IndexOf(words);
                    textBox.Select(startPosition, words.Length);
                    textBox.SelectedText = replaceText;
                    return ReplaceAllTextBox(ref textBox, findText, replaceText, register);
                }
                else
                {
                    MessageBox.Show(«Замены произведены успешно.»,  «Заменить всё», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else if (register == false)
            {
                string text = textBox.Text.ToLower();
                string words = findText.ToLower();
                if (text.Contains(words))
                {
                    int startPosition = text.IndexOf(words);
                    textBox.Select(startPosition, findText.Length);
                    textBox.SelectedText = replaceText;
                    return ReplaceAllTextBox(ref textBox, findText, replaceText, register);
                }
                else
                {
                    MessageBox.Show(«Замены произведены успешно.», «Заменить всё», MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return 0;
        }


        public static void mEditEnableds(ref TextBox notebox, ref ToolStripMenuItem mEditCopy, ref ToolStripMenuItem mEditCut, ref ToolStripMenuItem mEditDel)
        {
            if (notebox.Text.Length < 1)
            {
                mEditCopy.Enabled = false;
                mEditCut.Enabled = false;
                mEditDel.Enabled = false;
                mEditFind.Enabled = false;
                mEditGo.Enabled = false;
            }
            else
            {
                mEditCopy.Enabled = true;
                mEditCut.Enabled = true;
                mEditDel.Enabled = true;
                mEditFind.Enabled = true;
                mEditGo.Enabled = true;
            }
        }


        public static void StatusAnalize(ref TextBox notebox, ref ToolStripStatusLabel statusLinesCount, ref ToolStripStatusLabel statusWordsCount, ref ToolStripStatusLabel statusCharSpaceCount, ref ToolStripStatusLabel statusCharCount)
        {
            string text = notebox.Text;
            // Количество строк в тексте
            statusLinesCount.Text = notebox.Lines.Count().ToString();
            // Количество слов в тексте
            statusWordsCount.Text = text.Split(new Char[] { ‘ ‘, ‘\t’, ‘\n’, ‘\r’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’, ‘*’, ‘(‘, ‘)’, ‘-‘,
                ‘_’, ‘+’, ‘=’, ‘[‘, ‘{‘, ‘]’, ‘}’, ‘/’, ‘\\’, ‘|’, ‘»‘, ‘:’, ‘;’, ‘.’, ‘,’, ‘>’, ‘<‘ }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
            // Количество символов без пробелов
            statusCharCount.Text = text.Replace(» «, «»).Replace(«\t», «»).Replace(«\n», «»).Replace(«\r», «»).ToCharArray().Length.ToString();
            // Количество символов с пробелами
            statusCharSpaceCount.Text = text.ToCharArray().Length.ToString();
        }
    }
}

SearchForm.cs

Переходим к коду формы SearchForm.cs. В нём мы определим ту самую переменную из класса TextWork.cs, по которой метод поиска определяет с какой позиции начать выполнять операцию, а также напишем код для использования этого класса.

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


namespace NewNoteBlock
{
    public partial class SearchForm : Form
    {
        public SearchForm()
        {
            InitializeComponent();
        }


        private void SearchForm_Shown(object sender, EventArgs e) // Событие при открытии формы поиска и замены
        {
            tbFind.Focus();
        }


        int findCutLength = 0; // На сколько символов обрезаем текст для поиска


        private void tbFind_TextChanged(object sender, EventArgs e) // Cобытие при изменении текста в tbFind
        {
            findCutLength = 0;
        }


        private void tbReplace_TextChanged(object sender, EventArgs e) // Событие при изменении текста в tbReplace
        {
            findCutLength = 0;
        }


        private void cbReg_CheckStateChanged(object sender, EventArgs e) // Событие при изменении статуса cbReg
        {
            findCutLength = 0;
        }


        private void SearchForm_FormClosing(object sender, FormClosingEventArgs e) // Событие при закрытии формы (до закрытия)
        {
            findCutLength = 0;
        }


        private void butFind_Click(object sender, EventArgs e) // Кнопка «Найти»
        {
            MainForm main = this.Owner as MainForm;
            if (main != null)
            {
                if (cbReg.CheckState == CheckState.Checked)
                {
                    TextWork.FindTextBox(ref main.notebox, tbFind.Text, ref findCutLength, true);
                }
                else
                {
                    TextWork.FindTextBox(ref main.notebox, tbFind.Text, ref findCutLength, false);
                }
            }
        }


        private void butReplace_Click(object sender, EventArgs e) // Кнопка «Заменить»
        {
            MainForm main = this.Owner as MainForm;
            if (main != null)
            {
                if (cbReg.CheckState == CheckState.Checked)
                {
                    TextWork.ReplaceTextBox(ref main.notebox, tbFind.Text, tbReplace.Text, ref findCutLength, true);
                }
                else
                {
                    TextWork.ReplaceTextBox(ref main.notebox, tbFind.Text, tbReplace.Text, ref findCutLength, false);
                }
            }
        }


        private void butReplaceAll_Click(object sender, EventArgs e) // Кнопка «Заменить всё»
        {
            MainForm main = this.Owner as MainForm;
            if (main != null)
            {
                if (cbReg.CheckState == CheckState.Checked)
                {
                    TextWork.ReplaceAllTextBox(ref main.notebox, tbFind.Text, tbReplace.Text, true);
                }
                else
                {
                    TextWork.ReplaceAllTextBox(ref main.notebox, tbFind.Text, tbReplace.Text, false);
                }
            }
        }


        private void butCancel_Click(object sender, EventArgs e) // Кнопка «Отмена»
        {
            this.Close();
        }
    }
}

GoToForm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace NewNoteBlock

{

    public partial class GoToForm : Form

    {

        public GoToForm()

        {

            InitializeComponent();

        }

        private void butGo_Click(object sender, EventArgs e) // Кнопка «Перейти к строке»

        {

            MainForm main = this.Owner as MainForm;

            if (main != null)

            {

                int lineNumber = Convert.ToInt32(tbLineNum.Text);

                if (lineNumber > 0 && lineNumber <= main.notebox.Lines.Count())

                {

                    main.notebox.SelectionStart = main.notebox.GetFirstCharIndexFromLine(Convert.ToInt32(tbLineNum.Text) — 1);

                    main.notebox.ScrollToCaret();

                    this.Close();

                }

            }

        }

        private void butCancel_Click(object sender, EventArgs e) // Кнопка «Отменить»

        {

            this.Close();

        }

    }

}

Подсчет количества строк, слов, символов с пробелами и без

Метод для подсчета мы написали. Вызывать его будем через событие «notebox_TextChanged» (Событие при изменении текста в notebox) в форме MainForm.cs. Там уже есть код для изменения значения tbChange. Добавим в это событие строку:

TextWork.StatusAnalize(ref notebox, ref statusLinesCount , ref statusWordsCount, ref statusCharSpaceCount, ref statusCharCount);


Также добавим строку для активации пунктов меню «Правка» только при наличии текста:

TextWork.mEditEnableds(ref notebox, ref mEditCopy, ref mEditCut, ref mEditDel, ref mEditFind, ref mEditGo);

Меню — «Формат»

Добавим на форму MainForm.cs элемент FontDialog1 (FontDialog). Для клика по элементу меню Формат — «Шрифт» напишем код:

fontDialog.Font = notebox.Font;
DialogResult = fontDialog.ShowDialog();
if (DialogResult == DialogResult.OK)
{
    notebox.Font = fontDialog.Font;
}

Для события «CheckStateChanged» элемента меню Формат — «Перенос по словам» напишем код:

if (mFormatTransfer.CheckState == CheckState.Checked)
{
    notebox.WordWrap = true;
    notebox.ScrollBars = ScrollBars.Vertical;
    mEditGo.Enabled = false;
    statusLab1.Visible = false;
    statusLinesCount.Visible = false;
}
else
{
    notebox.WordWrap = false;
    notebox.ScrollBars = ScrollBars.Both;
    mEditGo.Enabled = true;
    statusLab1.Visible = true;
    statusLinesCount.Visible = true;
}

Видимость строки состояния

Для события «CheckStateChanged» элемента меню Вид — «Строка состояния» напишем код:

if (mViewStatusStrip.CheckState == CheckState.Checked)

{

    statusStrip.Visible = true;

}

else

{

    statusStrip.Visible = false;

}

О программе

Для клика по элементу меню Справка — «О программе» пишем:

AboutForm about = new AboutForm();
about.Show();

На этом создание текстового редактора завершено. У нас получился полноценный текстовый редактор, не просто не уступающий функционалу Блокнота Windows, а в чем-то даже превосходящий. По желанию, вы можете добавить свои иконки и изображения для придания дополнительной красоты. Полностью готовый проект текстового редактора вы можете скачать на странице проектов и статей.Спасибо за внимание!

Всем привет,
Сегодня мы будем делать редактор текстовых файлов, который будет уметь открывать уже существующие файлы и создать новые txt-файлы.
Кому читать дальше лень, могут скачать готовый проект [download-attachment id=»244″ title=»SimpleTextEditor»]

Поехали!

1)Создаем WinForms проект называем его, например, WinFormsApp_SimpleTextEditor
2) Кидаем на форму textBox и 2 кнопки, св-во name 1 кнопки = buttonOpen, 2-ой кнопки name = buttonSave.
+Anchor: bottom,right — для обеих кнопок.

textBox св-ва:
Anchor: Top, Bottom,Left,Right
ScrollBars: Vertical

На выходе должно получиться так:

3) Теперь кидаем на форму 2 диалоговых окна:

OpenFileDialog — св-ва:
+очищаем FileName,
+задаем для title значение «OPEN»

SaveFileDialog — св-ва:
+для title значение «SAVE»

Нажимаем 2 раза на кнопку Open и переходим в код:
пишем следующее:

private void buttonOpen_Click_1(object sender, EventArgs e)
{
   if (openFileDialog1.ShowDialog()== DialogResult.OK) //Проверяем был ли выбран файл
   {
       textBox1.Clear(); //Очищаем textBox
       openFileDialog1.Filter = "Text Files (*.txt)|*.txt"; //Указываем что нас интересуют только текстовые файлы
       string fileName = openFileDialog1.FileName; //получаем наименование файл и путь к нему.
       textBox1.Text = File.ReadAllText(fileName, Encoding.GetEncoding(1251)); //Передаем содержимое файла в textBox
   }
}

———————
Теперь «Сохранение»:
———————

private void buttonSave_Click_1(object sender, EventArgs e)
{
     saveFileDialog1.Filter = "Text Files|*.txt";//Задаем доступные расширения
     saveFileDialog1.DefaultExt = ".txt"; //Задаем расширение по умолчанию
     if (saveFileDialog1.ShowDialog() == DialogResult.OK) //Проверяем подтвердение сохранения информации.
     {
         var name = saveFileDialog1.FileName; //Задаем имя файлу
         File.WriteAllText(name, textBox1.Text,Encoding.GetEncoding(1251)); //Записываем в файл содержимое textBox с кодировкой 1251
     }
     textBox1.Clear();
}

Запускаем — проверяем сохранение:

Теперь открывает ранее сохраненный файл:

Все работает!

Если у тебя тоже получилось, ставь лайк.

  • Текстовый редактор в командной строке windows
  • Твикер windows 10 официальный сайт
  • Твикер для windows 10 про
  • Твикер для windows 10 на русском торрент
  • Твикер windows 10 скачать торрент