How to Undo and Redo in C# (Rich Text Box)

前端 未结 2 934
囚心锁ツ
囚心锁ツ 2021-01-19 16:43

I\'ve been trying to get undo and redo working in my text editor for about 3 days now. It\'s doing my head in.

I have a text box (n

2条回答
  •  一向
    一向 (楼主)
    2021-01-19 16:54

    You can have the RichTextBox build the undo stack for you word by word, plus keep track of the caret position, by handling one of the KeyDown-, KeyPress- or KeyUp events like this:

     private void rtb_KeyDown(object sender, KeyEventArgs e)
        {
            // Trick to build undo stack word by word
            RichTextBox rtb = (RichTextBox)sender;
            if (e.KeyCode == Keys.Space)
            {
                this.SuspendLayout();
                rtb.Undo();
                rtb.Redo();
                this.ResumeLayout();
            }
            // eztnap
        }
    

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

提交回复
热议问题