Emo
Emo

Reputation: 566

Prevent images in rich text box

I am working on a C# winForms application where I am using lots of RichTextBoxes. I found out that if I copied an image and pasted that in any RichTextBox, the image would be posted. Is there a way not to allow images to be pasted in the RichTextBox. In other words, to only allow keyboard characters.

Upvotes: 3

Views: 2527

Answers (3)

blitz_jones
blitz_jones

Reputation: 1078

The problem with the answer above is that it doesn't work in cases where there is mixed content. For example if you highlight a few rows from a spreadsheet and paste into a richtextbox you end up with more than just the raw text. I think the better solution is below:

    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;
        }            
    }

EDIT: The method below was shared by MrCC and is a more direct / better approach than my method above.

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.V)
        {
            if (Clipboard.ContainsText())
                richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Text));
            e.Handled = true;
        }
    }

Upvotes: 2

Emo
Emo

Reputation: 566

I was able to answer my question. Here it is in case someone else was looking for it.

private void InputExpressionRchTxt_KeyDown(object sender, KeyEventArgs e)
{
    bool ctrlV = e.Modifiers == Keys.Control && e.KeyCode == Keys.V;
    bool shiftIns = e.Modifiers == Keys.Shift && e.KeyCode == Keys.Insert;
    if (ctrlV || shiftIns)
        if (Clipboard.ContainsImage())
            e.Handled = true;
}

Upvotes: 2

zzfima
zzfima

Reputation: 1565

Maybe, you can catch paste event and check what object copied to RichTextBox. If it Image, just delete it.

Upvotes: 0

Related Questions