I'm working on a very simple Undo feature for a TextBox and I've got a weird problem. When I try to take strings from the Stack
that holds all the changes and put them inside the Textbox I don't see any changes.
I made a little Debug Label to check if this is really working or not. I found out that it is working in the label, but in the Textbox it uses its own Undo functions.
Is there a way to cancel or override the Textbox Undo and use my own function?
Here is sample code from the change I made:
private void Form1_KeyDown(object sender, KeyEventArgs e)
if (e.KeyCode == Keys.Z && (ModifierKeys & Keys.Control) == Keys.Control)
{
nameTextBox.Text = undoName.GetLastChange(); //--> not working
undoDebuglabel.Text = undoName.GetLastChange(); --> working
}
}
The GetLastChange() is getting the info from a Stack
inside the class.
It's like the Textbox is not letting me to see the changes.
Could it be because I'm using the same shortcut, CTRL + Z
to do it?
Clear the Textbox's own stack by using the ClearUndo method. Try this:
nameTextBox.ClearUndo();
nameTextBox.Text = undoName.GetLastChange();
You can create your own TextBox to handle history by inheriting from System.Windows.Forms.TextBox. Take a look at my sample:
public class HistoryTextBox: System.Windows.Forms.TextBox
{
bool ignoreChange = false;
List<string> storage = null;
protected override void OnCreateControl()
{
base.OnCreateControl();
//init storage...
storage = new List<string>();
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
//save change to storage...
if (!ignoreChange)
{
storage.Add(this.Text);
}
}
public void Undo()
{
if (storage.Count > 0)
{
this.ignoreChange = true;
this.Text = storage[storage.Count - 1];
storage.RemoveAt(storage.Count - 1);
this.ignoreChange = false;
}
}
}
Everytime you need to undo just call:
historyTextBox1.Undo();
This class will give you multiple histoy records.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With