RichTextBox Undo Adding Spaces

感情迁移 提交于 2019-12-13 04:09:55

问题


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 \n from one line, and more text below like this:

, then press delete, and then undo, it seems to undo this \n character twice.

回答1:


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?




回答2:


I think I've worked it out. When you highlight text like this:

you also include the \n character at the end of the last line that I've pointed to. However when you press delete, the RTB doesn't actually delete this character. So when you are undoing the delete, you have to remove any trailing \n characters, because they aren't actually being deleted.

来源:https://stackoverflow.com/questions/4231830/richtextbox-undo-adding-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!