Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

c# - RichTextBox Undo Adding Spaces

I've created my own undo system for the RichTextBox whereby whenever you do something an undo action is added to a stack, and when you press undo, this action is undone.

This behavior works perfectly with all controls I've implemented it for, except for RichTextBoxes. I have reduced the system down to its simplest elements, where whenever you press delete, it adds the current selected text and its index to a stack, and when you undo this, it puts the text back at this index.

Here is the code with the simplest elements stripped out (like the actual reading of the text file):

// Struct I use to store undo data
public struct UndoSection
{
    public string Undo;
    public int Index;

    public UndoSection(int index, string undo)
    {
        Index = index;
        Undo = undo;
    }
}

public partial class Form1 : Form
{
    // Stack for holding Undo Data
    Stack<UndoSection> UndoStack = new Stack<UndoSection>();

    // If delete is pressed, add a new UndoSection, if ctrl+z is pressed, peform undo.
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
            UndoStack.Push(new UndoSection(textBox1.SelectionStart, textBox1.SelectedText));
        else if (e.Control && e.KeyCode == Keys.Z)
        {
            e.Handled = true;
            UndoMenuItem_Click(textBox1, new EventArgs());
        }
    }

    // Perform undo by setting selected text at stored index.
    private void UndoMenuItem_Click(object sender, EventArgs e)
    {
        if (UndoStack.Count > 0)
        {
                    // Save last selection for user
            int LastStart = textBox1.SelectionStart;
            int LastLength = textBox1.SelectionLength;

            UndoSection Undo = UndoStack.Pop();

            textBox1.Select(Undo.Index, 0);
            textBox1.SelectedText = Undo.Undo;

            textBox1.Select(LastStart, LastLength);
        }
    }
}

However if you select just the from one line, and more text below like this: alt text, then press delete, and then undo, it seems to undo this character twice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've set this code up and it seems to do what you want it to do for me with a textbox and a richtextbox, I was unable to get extra spaces to be removed or added. Is there a specific order of operations that I could try to recreate your issue?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...