2010-11-20 61 views
0

我已經爲RichTextBox創建了我自己的撤消系統,因此無論何時您執行某項操作時撤消操作都會添加到堆棧中,並且當您按下撤消操作時,此操作將被撤消。RichTextBox撤消添加空格

此行爲完全適用於我爲其實施的所有控件,RichTextBoxes除外。我已經將系統簡化爲最簡單的元素,無論何時按下delete,它都會將當前選定的文本及其索引添加到堆棧中,並且在撤消此操作時,會將文本放回到此索引處。

這裏是剝離出來的簡單元素的代碼(如文本文件的實際讀取):

// 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); 
     } 
    } 
} 

不過,如果你只選擇從一條線的\ n和下面更多的文字是這樣:alt text,然後按刪除,然後撤消,它似乎撤消這個\ n字符兩次。

+0

你有通過代碼?可能的話,輸出堆棧上的所有東西,然後重新堆疊堆棧? – MunkiPhD 2010-11-22 01:55:39

回答

0

我想我已經完成了。當你像下面這樣突出顯示文本時:alt text你還在我指出的最後一行的末尾加入了\ n字符。但是,當您按刪除時,RTB實際上並未刪除此字符。所以當你撤銷刪除時,你必須刪除任何結尾的\ n字符,因爲它們實際上並未被刪除。

0

我已經設置了這個代碼,它似乎做你想讓它爲我做一個文本框和一個richtextbox,我無法獲得額外的空間被刪除或添加。是否有特定的操作順序,我可以嘗試重新創建您的問題?

+0

我終於找出了導致問題的原因,只是沒有解決方案:當您從上一行中以\ n字符開始選擇時,刪除選擇,然後撤消該選擇,\ n以某種方式添加了兩次。 – Miguel 2010-11-22 01:44:23