簡體   English   中英

如何防止系統剪貼板圖像數據粘貼到WPF RichTextBox中

[英]How can I prevent system clipboard image data being pasted into a WPF RichTextBox

我目前有一些代碼可以攔截所有剪切,復制和粘貼事件到WPF中的RichTextBox中。 這些設計用於剝離除純文本之外的所有內容,並且不允許粘貼除純文本之外(通過使用Check Clipboard.ContainsText()方法。)這似乎在防止所有此類操作從表單內部成功方面是成功的。 用戶只能在周圍復制,剪切和粘貼文本,不允許使用圖像/音頻數據/隨機垃圾。

但是,如果我使用PrintScreen函數並將其粘貼到RichTextBoxes之一中,則將圖像粘貼到其中(而不是所需的行為。)但是,如果您嘗試將此圖像從一個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(etc)方法本質上會在允許任何操作之前檢查僅文本存在。

這里似乎有兩個剪貼板在工作,其中一個不是我要限制/鎖定。 有誰知道它的技術性,以及可以有效鎖定和自定義所有剪貼板活動(窗體和系統)的任何方式嗎?

提前致謝。

實際上,您不需要像捕獲KeyDown事件那樣的任何技巧(也不會阻止通過上下文菜單進行粘貼或進行拖放)。 有一個特定的附加事件: DataObject.Pasting

XAML:

<RichTextBox DataObject.Pasting="RichTextBox1_Pasting" ... />

代碼隱藏:

    private void RichTextBox1_Pasting(object sender, DataObjectPastingEventArgs e)
    {
        if (e.FormatToApply == "Bitmap")
        {
            e.CancelCommand();
        }
    }

它可以防止所有形式的粘貼(Ctrl-V,右鍵單擊->粘貼,拖放)。

如果要比這更聰明,也可以用僅包含要支持的格式的DataObject替換DataObject(而不是完全取消粘貼)。

對於用戶來說可能有點寬容,但是您可以像在粘貼之前劫持並清除剪貼板一樣簡單。 只需鈎住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();
}

不是最巧妙的解決方案,而是可以解決的。

我認為如果您的目標是只允許粘貼純文本,那么這可能是一種更好的方法:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.V)
        {
            if (Clipboard.GetData("Text") != null)
                Clipboard.SetText((string)Clipboard.GetData("Text"), TextDataFormat.Text);
            else
                e.Handled = true;
        }            
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM