Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 741
Emo Avatar asked Dec 29 '25 03:12

Emo


2 Answers

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;
}
like image 113
Emo Avatar answered Dec 31 '25 17:12

Emo


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;
        }
    }
like image 41
dizzy.stackoverflow Avatar answered Dec 31 '25 19:12

dizzy.stackoverflow