A printable extension to .NET's RichTextBox


VS .NET (works with RC1, should work with BETA2 as well)


With VC++ 6.0 everything was simple. You had a wizard create a project using a document/view architecture and chose CRichEditView as view class and MFC framework gave you print preview and printing out of the box without need to put additional work in it.

Then came VS.NET. Admittedly, the new features of the dotnet framework are great, but up until now it lacked an easy way of bringing the contents of a richedit control to your printer.

After many hours of searching for a suitable way to incorporate printing services into my project I finally started resorting to Win32 API calls again, since none of the suggestions you find on the web or on MSDN delivered anything practical.

After many more hours of fiddling with device contexts, page margins etc. I finally succeeded in creating an extension for .NET's RichTextBox control with additional methods for doing print output in a way it should have been included with .NET from the beginning (IMHO).


In fact the only API function I had to encapsulate was to send EM_FORMATRANGE to the control. Since this particular message receives a pointer to a struct as one parameter I had to dwell into the depths of .NET's InteropServices, but in the end it worked out quite nicely.

First the required structs had to be introduced to .NET:

typedef struct tagRECT
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;

translated to

[ StructLayout( LayoutKind.Sequential )]
private struct RECT 
    public int left;
    public int top;
    public int right;
    public int bottom;

Note that API's LONG type maps to an int in .NET, not to long or you'll get some weird results.

The FORMATRANGE struct handled much the same way, marshalling the device context handles to IntPtr.

Next came the declaration of the SendMessage API function:

[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd,
                                         int msg,
                                         IntPtr wParam,
                                         IntPtr lParam);

Although you'll find an example in MSDN where SendMessage receives int as type for wParam and lParam, you need IntPtr here because a pointer to a FORMATRANGE struct has to be marshalled.

The rest went quite straightforward. To put the contents of the FORMATRANGE struct into an IntPtr parameter you have to use a static method

after allocating enough space with
Don't forget to release the memory afterwards by calling
(the Garbage Collector won't help you here).


Use RichTextBoxEx the same way you would use a regular RichTextBox.

When it comes to printing, you can use the method FormatRange() to render the contents of your RichTextBoxEx control according to the PrintPageEventArgs parameter you receive in the PrintPageEvent event handler function.

When you're done printing call the method FormatRangeDone() to release any cached information the WIN32 RichEdit control still is holding.

Have a look at the sample project if you're unsure on how to use the control.


Download demo project - 7 Kb
Download source (RichTextBox assembly and demo project) - 15 Kb


  • Cheap GHD IV styler venta, descuento ghd rosa 2013 en España

    Posted by jkcjnv808 on 07/25/2013 09:38pm

    Todavía puedo utilizar mi loción para después frívola, peluquería, pero es tan increíblemente suave. En general, estoy muy impresionado. Compre personas ghd baratas que no tienen mucho dinero, por lo que es tensa, su cartera, puedo decir que es totalmente la pena el dinero! No me devolvieran mi dinero, a prueba de humedad, también he escuchado una buena protección térmica GHD (proteger plancha de pelo, secador de pelo, y creo que cuesta unos 15 euros, pero evite el abuso excesivo del cabello. [url=http://comprarghd.webgarden.com/]GHD España[/url] pelo ghd es hermosa arma secreta peinado de una mujer. El famoso GHD es el encanto de la manera de conquistar a la mujer exigente y estilista? En primer lugar, entendemos el pelo ghd en los principales productos funktioner.GHD enderezador principales, técnica de calentamiento, principalmente de cerámica, el uso de la producción de calentador de cerámica y Corea del Sur, placa caliente, y se implanta la nanotecnología, la tecnología de infrarrojos y la tecnología de iones negativos, los productos , en su mayoría a cargo de luz de la superficie, elegante excelente calidad. Todos los productos son fabricados de acuerdo con la norma británica GS, seguro y confiable. rosa ghd sigue siendo el producto más vendido en 2011, esta GHD Qué encanto? [url=http://planchaspeloghd.cabanova.com/]planchas ghd baratas[/url] Jugar en un día ajetreado, lo primero que queremos tratar de relajarse, baño de agua tan caliente es la mejor manera de bloquear uno cansado día. Cuando te lavas el pelo no hay manera de deshacerse inmediatamente de, así que si usted necesita ayuda con un secador de pelo para secar el pelo. No hay secador de pelo, entonces usted tiene que esperar a que el pelo se seque lentamente. De esta manera, una pérdida de tiempo no le gusta el cabello seco, lo que debe hacer si se pone al día con los acontecimientos. Así que hay que utilizar un secador de pelo ghd. El secador de pelo, siempre y cuando usted compra nuestros alisadores de pelo ghd, usted puede conseguir fácilmente. Nuestro pelo lacio ghd con un secador de pelo de los accesorios, tarjetas, hermoso espejo y alisadores ghd etc paquetes especiales, las instalaciones, no sólo puede guardar una bolsa que puede soplar el pelo seco y, a continuación, utilizar la ghd para crear un nuevo peinado. Realmente servir a dos propósitos.

  • FGVWg deo EFIw

    Posted by qBLYwNoRuo on 06/17/2013 04:45pm

    generic vicodin online vicodin overdose liver failure - vicodin withdrawal infant

  • Lightweight stylish – Nike Free TR Right in shoot up 2013 3 series

    Posted by Tufffruntee on 04/24/2013 02:00pm

    Nike Manumitted TR Stalwart 3 noteworthy features is to exploit the new forge: Nike Self-ruling 5 soles improved bending Scratch; supplemental tractor imitate making training more focused when; lighter ballast, the permeability is stronger, and more in fashion shoe designs not not aim for shoes [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] more serene wearing, barefoot training caress, but also more fashionable appearance. Nike Manumitted TR Fitting 3 provides unequalled lateral stability, you can take the legs in the leg during training. Strong vamp majuscule letters breathable grate, disgrace foam's solitary design can be [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] seen by virtue of it. Lightweight, rugged, reduce foam means used at hand merest some seams, more flexible, help is stronger. Demand more advance, role of a training utilize, foam neck in more parts of the destitution for flexibility, effervescence loose. Use double tongue moisture wicking synthetic materials, flat on your feet, refrain from maintenance feet desiccated and comfortable. Phylite [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] midsole offers lightweight revolt level, special durability and stable outsole can do to greatly reduce the all-embracing weight of the shoe. Qianzhang pods on the outsole and heel-shaped Green rubber enhances the shoe multi-directional drag on odd surfaces.

  • Nike Display Max 1 FB press, father a eager color character, the brand-new shoes

    Posted by Geozyoceada on 04/22/2013 07:11pm

    In the summer in a pane interior the serene sprite seems to be a good preferred, but if the sprite "feet"? Resolution also fork out you a frisk, take a sustenance! This summer, Nike and Sprite [url=http://northernroofing.co.uk/roofins.cfm]nike free run uk[/url] and his sneakers to a blend of classic snow spread of unripened, off-white and indecent color blueprint in the time-honoured Nike Air Max 1 shoes let it be known a food chill scent.[url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] Summer is the yet to select a purified shoe, shoes should be a creditable choice. Qualifying series Nike Publicize Max HomeTurf city recently finally comes up, this series in the immortal Air Max shoes to London, Paris and Milan the three paid encomium to the iconic megalopolis of Europe, combined with the characteristics of the three cities, Air Max 1 HYP,Make public Max 90 HYP,Air Max 1 and shoes such as Make public Max 95, combined [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] with the Hyperfuse, as well as a variety of materials, such as suede, Whether you hankering practicable or retro-everything.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date