A printable extension to .NET's RichTextBox

Environment:

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

Description:

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).

Coding:

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;
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

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

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

Usage:

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.

Downloads

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


Comments

  • 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.

    Reply
  • FGVWg deo EFIw

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

    generic vicodin online vicodin overdose liver failure - vicodin withdrawal infant

    Reply
  • 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.

    Reply
  • 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.

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

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds