[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Save a RichTextBox image in C#

[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. rtb.Update(); // 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)) { gr.CopyFromScreen( 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 experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.