How to Insert image into RichTextBox in C#

By FoxLearn 7/18/2024 8:06:47 AM   8.83K
To insert an image into a RichTextBox in a C# Windows Forms Application, you can use the Clipboard class to copy the image to the clipboard and then paste it into the RichTextBox.

How to Insert an image into a RichTextBox in C#

Drag and drop the RichTextBox, Button controls from Visual Studio toolbox to your form designer, then you can design your form as shown below.

c# insert image to richtextbox

Adding a click event handler to the Open button allows you to trigger the image insertion process in RichTextBox control in C#.

// Handle the click event of the button to insert the image.
private void btnOpen_Click(object sender, EventArgs e)
{
    // Get the selected image file path
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.png; *.bmp";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            // Load the image from file, then copy the image to clipboard
            Clipboard.SetImage(Image.FromFile(ofd.FileName));
            // Paste the image into the RichTextBox
            richTextBox.Paste();
        }
    }
}

In this example, we handle the click event of a button (btnOpen_Click).

Next, We use an OpenFileDialog to allow the user to select an image file. Once the user selects an image file, we load the image from the file using Image.FromFile(), then we copy the image to the clipboard using Clipboard.SetImage().

Finally, we paste the image into the RichTextBox using richTextBox.Paste().