Search code examples
c#winformsrichtextboxundoredo

How to get RichTextBox Undo to work better?


I am trying to write a text editor using RichTextBox. My concern is now about Undo and possibly Redo features of RichTextBox.

When I start writing in text box, say 1 minute! if I call Undo method, all it does is just I beleive clearing or resetting richtextbox again. How can I get it to work that it can do better, like Undoing last added word, or last added new line...I mean usual things you expect from Undo function. (The same counts for Redo also!)

Is there properties or some options to achive this? Or I have to implement my own code?


Solution

  • You can save the lastest Data and when you want to undo you can change to now data to last data! lastest data can be set anytime that you want!

    I Make a winForm with a richTextBox and a button that button undo the wrote text:

    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 test
    {
    
    
    public partial class Form1 : Form
    {
        List<string> LastData = new List<string>();
    
        int undoCount = 0;
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            LastData.Add(richTextBox1.Text);
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Text = LastData[LastData.Count - undoCount - 1];
                ++undoCount;
            }
            catch { }
        }
    
        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            LastData.Add(richTextBox1.Text);
            undoCount = 0;
        }
    }
    }
    

    but I didn't find any better and organized way and you can change

    LastData.Add(richTextBox1.Text);
    undoCount = 0;
    

    to save new words or new line

    update: if you want to save the Ram you can delete the first data on list after many undo saving.