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:
Able to open files and display them into the editor:
- Line/Column numbers also show according to where your cursor is selected
Able to see an example of the color before you choose it:
- 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:
Prerequisites
Requires Visual Studio 2017 or higher to run.
Built With
- C# Windows Forms
Contributing
[Coming Soon]
Authors
- Hunter — Initial 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
SimpleTextor
Offering users a rich text editing experience is essential for many desktop applications, whether used to edit articles, create formatted reports, or just add notes with links and images. Have you ever wondered how simple it is to bring this capability into your own app?
ComponentOne offers the C1Editor control that provides a simple yet effective way of adding rich text editing capabilities to your WinForms applications. In this blog, we will walk you through two simple ways to integrate this control so that users can easily create and edit rich content:
- Build a Custom Toolbar to Implement Features via Code-Behind
- Use the C1EditorRibbon for the Built-In Features (No Code Required!)
Ready to Get Started? Download ComponentOne Today!
To demonstrate both approaches, we’ll create a simple WinForms application that allows users to load HTML or XHTML files, format the content, make edits, and save their changes. So, let’s get started!
Build a Custom Toolbar to Implement Features via Code-Behind
This approach is perfect when you want full control over the editor’s features and to design your own toolbar. By handling actions in the code behind, the editing experience can be customized based on the application’s requirements.
For this demo, let’s implement some essential features of a rich text editor:
- File Operations — Create a new file, open an existing one, and save changes.
- Font Formatting — Change the font size and font face of the editor’s content.
Let’s start by creating a simple WinForms application and following the steps below:
- Open Visual Studio and select File | New | Project to create a new Windows Form App.
2. Use the NuGet Package Manager to install the C1.Win.Editor and C1.Win.Command packages in your project.
3. Drag and drop the C1ToolBar and C1Editor control from the toolbox onto the form. In the C1ToolBar, place the buttons and combo boxes for the feature implementation.
The form layout should look like the image below:
Now that our layout is ready, let’s add the functionality behind those toolbar buttons and combo boxes.
Implementing File Operations
First, we will implement basic file operations: New, Open, and Save.
New — Clicking the ‘New’ button will clear the editor content after prompting the user to save any unsaved changes:
private void CreateNewDocument()
{
// Removes the "body" element from the editor, effectively creating a new document
editorView.RemoveElementAsync(null, "body");
}
Open — Pressing the ‘Open’ button lets users load an existing HTML or XHTML file into the editor:
public void OpenDocument()
{
using (var dlg = new OpenFileDialog())
{
dlg.Filter = "HTML Files (*.html;*.htm)|*.html;*.htm|All Files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK && File.Exists(dlg.FileName))
{
// Load the document into the editor
editorView.LoadDocumentAsync(Path.GetFullPath(dlg.FileName));
// Apply default styles
editorView.SetDefaultStylesAsync(null, true);
}
}
}
Save: Clicking the ‘Save’ button allows users to store the current content in an HTML file:
public bool SaveDocument()
{
using (SaveFileDialog dlg = new SaveFileDialog())
{
// Set default file name and filters for the save dialog
dlg.FileName = "sampleFile";
dlg.Filter = "HTML Files (*.html;*.htm)|*.html;*.htm|All Files (*.*)|*.*";
dlg.DefaultExt = "html";
dlg.AddExtension = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
string filePath = dlg.FileName;
// Save the document asynchronously and check if the save operation was successful
if (editorView.SaveDocumentAsync(filePath) != null)
{
return true;
}
}
}
// Return false if the user cancels or the save fails
return false;
}
Adding Font Formatting Options
Now that our file operations are working, let’s add functionality to change the font family and font size of the text in the editor using the toolbar combo boxes. The step-by-step approach to achieve this is as follows:
- Load the Default Content and Enable Editing — Begin by loading a sample HTML file into the editor once it’s ready and turn on editing mode so users can make changes:
private void editorView_C1EditorReady(object sender, EventArgs e) { string filename = @"Resources\\bookClub.html"; if (File.Exists(filename)) { editorView.LoadDocumentAsync(Path.GetFullPath(filename)); editorView.DesignEdit = true; // Enable editing } }
2. Set Up the Font Combo Boxes with Initial Values: Next, fill the Font Face and Font Size combo boxes with some generic options:
private void InitializeFontGroup() { // Populate the Font Face combo box with available system fonts foreach (FontFamily fontFamily in FontFamily.Families) { fontFaceComboBox.Items.Add(fontFamily.Name); } // Populate the Font Size combo box with common font sizes foreach (int size in new int[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 }) { fontSizeComboBox.Items.Add(size.ToString()); } // Keep the font group combo boxes in sync with the current text selection UpdateFontGroupBasedOnCurrentTextSelection(); editorView.SelectedTextChanged += delegate { this.UpdateFontGroupBasedOnCurrentTextSelection(); }; }
3. Sync the Combo Boxes with the Selected Text: Using the code below, update the combo boxes to show the current font and size whenever users select some text:
private async void UpdateFontGroupBasedOnSelection() { Font font = await editorView.GetSelectionFontInfoAsync(); fontFaceComboBox.Text = font?.FontFamily.Name ?? ""; fontSizeComboBox.Text = font?.Size.ToString() ?? ""; }
4. Apply the Font and Size Changes: When users pick a new font or size from the combo boxes, we apply those changes to the selected text:
// handing selection changed for fontFaceComboBox private void fontFaceComboBox_SelectionChangeCommitted(object sender, EventArgs e) { UpdateFontOnSelection("Face"); } // handing selection changed for fontSizeComboBox private void fontSizeComboBox_SelectionChangeCommitted(object sender, EventArgs e) { UpdateFontOnSelection("Size"); } // method to update the select font based on the changes in the font group combo-boxes public async Task UpdateFontOnSelection(string fontParameter) { Font font = await editorView.GetSelectionFontInfoAsync(); if (font != null) { if (fontParameter == "Face") { string fontFamilyName = fontFaceComboBox.Text; editorView.SetFontAtSelectionAsync(new Font( fontFamilyName, font.Size, font.Style, font.Unit)); } else if (fontParameter == "Size") { editorView.SetFontAtSelectionAsync(new Font( font.FontFamily, float.Parse(fontSizeComboBox.Text), font.Style, GraphicsUnit.Point)); } } }
There you have it—our custom toolbar is set and working!
Use the C1EditorRibbon for the Built-In Features (No Code Required!)
Now, let’s make things even easier with another approach.
Instead of building the toolbar from scratch, we can simply use the C1EditorRibbon control already available in the form layout. This ready-made, Word-style ribbon is only available in the C1.Win.Editor package. All we need to do is place it on the form and connect it to the C1Editor control, as shown below:
// attach the editor control to the ribbon
editorRibbon.Editor = editorView;
Check out the following image to see it in action:
You can download the sample and follow along.
Ready to check it out? Download ComponentOne Today!
Conclusion
In this blog, we explored two ways to enhance your WinForms app with rich text editing—a manual approach with a custom toolbar and an effortless option with C1EditorRibbon. Whether you like customizing things your way or prefer a quicker plug-and-play setup, both approaches help you create a smooth and professional editing experience for your users.
You can experiment more with the C1Editor control by referring to its official documentation.
If you have any inquiries, please leave them in the comments section below. Happy Coding!
Step 1: Firstly we’re going to create a new Win Form Application project(I’ll call it Cioban Mini Text Editor).
Step 2: To our form we will add three buttons(one for saving the file,one for reading the file,and the other for font),an openfile dialog,a savefile dialog,a font dialog, and rich textbox.Also,we’ll ad a new namespace(System.IO).
Step 3: The design it’s done.Let’s start coding.
In my case:
button1 = open button;
button2 = save button;
button3 = the font button
This is the code
- 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;
- using System.IO;
- namespace Cioban_Mini_Text_Editor
- {
- public partial class Form1: Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- openFileDialog1.ShowDialog();
- if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFileDialog1.FileName.Contains(«.txt»))
- {
- string open = File.ReadAllText(openFileDialog1.FileName);
- richTextBox1.Text = open;
- }
- else
- {
- MessageBox.Show(«The file you’ve chosen is not a text file»);
- }
- }
- private void button2_Click(object sender, EventArgs e)
- {
- saveFileDialog1.ShowDialog();
- if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- string name = saveFileDialog1.FileName + «.txt»;
- File.WriteAllText(name, richTextBox1.Text);
- }
- }
- private void button3_Click(object sender, EventArgs e)
- {
- fontDialog1.ShowDialog();
- if (fontDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
- richTextBox1.Font = fontDialog1.Font;
- }
- }
- }
- }
Enjoy
Thanks guys.
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: