Save a RichTextBox image in C#


My post Get the image of a control or form, or a form’s client area in C# uses a control’s DrawToBitmap method to make it draw itself onto a bitmap. Unfortunately the RichTextBox control does not support that method.

Another approach you can take is to capture the part of the screen image above where the RichTextBox control lies. That’s the approach taken by the MSDN post how to save the content of richTextBox as jpg file?

In the following method I’ve modified the technique described by that post slightly so it captures the control’s client area.

public Bitmap RtbToBitmap(RichTextBox rtb)
    // Make sure the RichTextBox is fully painted.

    // Get the image.
    int width = rtb.ClientSize.Width;
    int height = rtb.ClientSize.Height;
    Bitmap bmp = new Bitmap(width, height);
    using (Graphics gr = Graphics.FromImage(bmp))
            rtb.PointToScreen(new Point(0, 0)),
            new Point(0, 0), rtb.ClientSize);
    return bmp;

This method updates the RichTextBox. It then gets the control’s client width and height. It then makes a bitmap of that size and creates an associated Graphics object. It uses the object’s CopyFromScreen method to copy the part of the screen image above the RichTextBox onto the bitmap.

Notice how the program uses the RichTextBox control’s PointToScreen method to convert the control’s upper left corner at (0, 0) to screen coordinates.

After copying the image onto the bitmap, the method returns the bitmap.

Note that this only works if the RichTextBox is not covered by some other control. For example, if another form lies on top of the control when the method runs, then it will grab an image of the other form.

Download the example to see additional details and to experiment with the program.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in controls and tagged , , , , , , , . Bookmark the permalink.