我目前有一些代码可以将所有剪切、复制和粘贴事件拦截到 WPF 中的 RichTextBox 中。这些设计用于去除纯文本以外的所有内容,并且不允许粘贴纯文本以外的内容(通过使用检查 Clipboard.ContainsText() 方法。)这似乎成功地防止了所有此类操作从内部 表格。用户只能复制、剪切和粘贴文本,不允许图像/音频数据/随机垃圾。
但是,如果我使用 PrintScreen 函数,并将其粘贴到其中一个 RichTextBox 中,图像将被粘贴(不是想要的行为。)如果您随后尝试将此图像从一个 RichTextBox 粘贴到另一个,它会赢让你(期望的行为)。
我当前覆盖的命令是使用
// Command handlers for Cut, Copy and Paste commands.
// To enforce that data can be copied or pasted from the clipboard in text format only.
CommandManager.RegisterClassCommandBinding(typeof(MyRichTextBox),
new CommandBinding(ApplicationCommands.Copy, new ExecutedRoutedEventHandler(OnCopy),
new CanExecuteRoutedEventHandler(OnCanExecuteCopy)));
CommandManager.RegisterClassCommandBinding(typeof(MyRichTextBox),
new CommandBinding(ApplicationCommands.Paste, new ExecutedRoutedEventHandler(OnPaste),
new CanExecuteRoutedEventHandler(OnCanExecutePaste)));
CommandManager.RegisterClassCommandBinding(typeof(MyRichTextBox),
new CommandBinding(ApplicationCommands.Cut, new ExecutedRoutedEventHandler(OnCut),
new CanExecuteRoutedEventHandler(OnCanExecuteCut)));
OnCopy(等)方法然后在允许任何操作之前实质上检查是否只有文本存在。
这里似乎有两个剪贴板在工作,其中一个我没有限制/锁定。有谁知道这方面的技术细节,以及可以有效锁定和自定义所有剪贴板事件(包括表单和系统)的任何方式?
提前致谢。
最佳答案
这对用户来说可能有点无情,但您可以像在粘贴前劫持和清除剪贴板一样简单地做到这一点。只需 Hook PreviewKeyDown(因为在 KeyUp 上它已经被插入)并在我们有图像并按下 Ctrl+V 时清除剪贴板:
public Window1()
{
InitializeComponent();
_rtf.PreviewKeyDown += OnClearClipboard;
}
private void OnClearClipboard(object sender, KeyEventArgs keyEventArgs)
{
if (Clipboard.ContainsImage() && keyEventArgs.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) != 0)
Clipboard.Clear();
}
这不是最巧妙的解决方案,但它可以解决问题。
关于c# - 如何防止将系统剪贴板图像数据粘贴到 WPF RichTextBox 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3970040/