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

穿精又带淫゛_ 提交于 2019-12-02 01:11:27

It might be a bit unforgiving for the user but you could do it as simple as hijacking and clearing the Clipboard before pasting. Just hook the PreviewKeyDown (since on KeyUp it´s already been inserted) and clear the clipboard if we´ve got an image and is pressing 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();
}

Not the neatest solution but it´ll do the trick.

Actually you dont need any hack like catching the KeyDown events (which wouldn't prevent pasting through the context menu or drag and drop anyway). There's a specific attached event for that: DataObject.Pasting.

XAML:

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

Code-behind:

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

It prevents all forms of pasting (Ctrl-V, right-click -> Paste, drag and drop).

If you want to be smarter than that, you can also replace the DataObject with one that contains only the formats you want to support (rather than completely cancelling the paste).

I think this is probably a better way if your goal is to just allow the plain text to be pasted:

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;
        }            
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!