Search code examples
c#imagewinformsclipboard

Can't paste Image from Clipboard to RichTextBox


I'm looking to programmatically convert a base64 string into an Image that I then insert into a richTextBox.

Right now I load the string into a stream and convert that into an Image. I then load that onto the Clipboard and attempt to paste. However, when I execute the code, nothing pastes into the richTextBox. After running the code, the image is properly set in my Clipboard and I am able to paste it manually into the richTextBox - it just doesn't seem to work programmatically.

Here's my code:

byte[] img_bytes = Convert.FromBase64String(imgStr);
using (var ms = new MemoryStream(img_bytes, 0, img_bytes.Length))
{
    Image img = Image.FromStream(ms, true);
    Bitmap imgb = (Bitmap)Bitmap.FromStream(ms);
    Clipboard.SetDataObject(img);
    Console.WriteLine(Clipboard.ContainsImage()); // Prints True
    richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
    Console.WriteLine(richTextBox1.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap))); // Prints True
    richTextBox1.Text += "\n";
}

Update: It appears that setting the text field after pasting the image deletes the image. I guess the question now is, how do I have both the image and the text?


Solution

  • It appears that setting a richTextBox's text attribute after pasting was deleting the image. I changed the line

    richTextBox1.Text += "\n";
    

    to

    Clipboard.SetText("\n");
    richTextBox1.Paste();
    

    which is a pretty terrible solution but it works and I'm on a deadline :) I'm open to other suggestions that are less hacky!