Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET RichTextBox undo

Tags:

undo

c#

winforms

I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.

Is there a way to make it so these changes are available for undo/redo?

like image 677
Adam Haile Avatar asked Nov 09 '08 01:11

Adam Haile


People also ask

How do you undo and redo using RichTextBox control?

Since the RichTextBox does the job for you, you just have to call rtb. Undo() or rtb. Redo() from wherever you need to.

What is RichTextBox?

The RichTextBox control enables you to display or edit flow content including paragraphs, images, tables, and more. This topic introduces the TextBox class and provides examples of how to use it in both Extensible Application Markup Language (XAML) and C#.

What is RichTextBox in Windows Form applications?

The Windows Forms RichTextBox control is used for displaying, entering, and manipulating text with formatting. The RichTextBox control does everything the TextBox control does, but it can also display fonts, colors, and links; load text and embedded images from a file; and find specified characters.


1 Answers

Here's just some code I decided to mess around with:

        string buffer = String.Empty;
        string buffer2 = String.Empty;
        public Form3()
        {
            InitializeComponent();
            this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);
            this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);
        }

        void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            buffer2 = buffer;
            buffer = richTextBox1.Text;
        }

        void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Z)
            {
                this.richTextBox1.Text = buffer2;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "Changed";
        }

It's basically me writing my own Undo feature. All I'm doing is storing the old value in one buffer variable, and the new value in a second buffer variable. Every time the text changes, these values get update. Then, if the user hits "CTRL-Z" it replaces the text with the old value. Hack? A little. But, it works for the most part.

like image 69
BFree Avatar answered Oct 05 '22 11:10

BFree