Richtextbox - on undo?
本文关键字:undo on Richtextbox | 更新日期: 2023-09-27 18:10:25
我需要能够检测"撤销"是否已被触发,以及它是否对我的RichTextBox
的内容有影响。
我在分钟内将内容输入RichTextBox
,并按Ctrl+Z,窗口似乎为我处理撤销。我希望能够编写代码,将被触发后,直接。我已经到处找了,但什么也没找到。
从。net 3.0开始,有一种简单的内置方法可以在执行撤销命令(以及其他命令)时获得通知:
CommandManager.RegisterClassCommandBinding(typeof(MyClass),
new CommandBinding(ApplicationCommands.Undo, OnUndo));
在静态构造函数(或其他地方)调用这行代码并添加一个静态方法:
private static void OnUndo(object sender, ExecutedRoutedEventArgs e)
{
//your code
}
WINFORM:
您可以利用KeyDown
事件并检测是否按下了Ctrl+Z:
richTextBox.KeyDown += new KeyEventHandler(richTextBox_KeyDown);
private void richTextBox_KeyDown(object sender, KeyEventArgs e){
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Z){
//undo detected, do something
}
}
WPF :
richTextBox.KeyUp += new KeyEventHandler(richTextBox_KeyUp);
void richTextBox_KeyUp(object sender, KeyEventArgs e) {
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Z) {
//undo detected, do something
}
}
我认为你必须自己实现它。我不知道有什么现成的活动能满足你的需要。
你可能还想看看监控的撤消框架。
这里是附加阅读
如果我没理解错的话,您是想比较Ctr+Z
前后的内容。
那么你应该这样做:
In XAML File:
<RichTextBox PreviewKeyDown="RichTextBox_PreviewKeyDown" KeyUp="RichTextBox_KeyUp" />
In CS File:
private void RichTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Z)
{
Console.WriteLine("After : " + new TextRange(((RichTextBox)sender).Document.ContentStart, ((RichTextBox)sender).Document.ContentEnd).Text);
}
}
private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Z)
{
Console.WriteLine("Before : " + new TextRange(((RichTextBox)sender).Document.ContentStart, ((RichTextBox)sender).Document.ContentEnd).Text);
}
}
然后,您将在应用程序的输出中看到您的RichTextBox的内容在Ctrl+Z
之前和之后。
我试过了,效果很好!
如前所述,可以使用CommandBindings
。我更喜欢绑定到每个control
,而不是绑定到特定类的所有控件。这可以通过以下方式完成:
this.richTextBox.CommandBindings.Add(
new CommandBinding(ApplicationCommands.Undo, this.RichTextBoxUndoEvent));
private void RichTextBoxUndoEvent(object sender, ExecutedRoutedEventArgs e)
{
e.Handled = true;
this.richTextBox.Undo();
}