How to: Print the contents of a RichTextBox control using Visual C #. NET

Source: Internet
Author: User

Overview This step-by-step guide describes how to print the contents of the RichTextBox control. the RichTextBox control does not provide any way to print RichTextBox content. You can extend the RichTextBox class to use the Em_formatrange message to send the contents of the RichTextBox control to an output device, such as a printer.

Creating RichTextBoxPrintCtrl ControlsThe following example shows how to extend the RichTextBox class and how to print the contents of a RichTextBox control using Em_formatrange.
  1. In Visual C #. NET, create a new class library project named RichTextBoxPrintCtrl. The Class1.cs is created by default.
  2. Change the name of the Class1.cs to RichTextBoxPrintCtrl.cs.
  3. In Solution Explorer, right-click References, and then click Add Reference.
  4. In the Add Reference dialog box, double-click System.Drawing.dll and System.Windows.Forms.dll, and then click OK.
  5. Replace the existing code in RichTextBoxPrintCtl.cs with the following code:
    Using system;using system.windows.forms;using system.drawing;using system.runtime.interopservices;using System.drawing.printing;namespace Richtextboxprintctrl{public class Richtextboxprintctrl:richtextbox{//convert the Unit used by the. NET Framework (1/100 inch)//and the unit used by Win32 API calls (twips 1/1440 inch) Private Const DOUBL e AnInch = 14.4; [StructLayout (layoutkind.sequential)] private struct rect{public int left;public int top;public int right;public int Bott Om;}         [StructLayout (layoutkind.sequential)]private struct charrange{public int cpmin;           First character of range (0 for start of doc) public int cpmax; Last character of range ( -1 for end of Doc)}[structlayout (layoutkind.sequential)]private struct formatrange{public intp             TR HDC;       Actual DC to draw onpublic IntPtr Hdctarget;                Target DC for determining text formattingpublic RECT RC;            Region of the DC to draw to (in twips) public RECT rcpage; Region of theWhole DC (page size) (in twips) public Charrange Chrg; Range of text to draw (see earlier declaration)}private const INT wm_user = 0x0400;private const int Em_formatrange = Wm_user + 57; [DllImport ("USER32.dll")]private static extern IntPtr SendMessage (IntPtr hWnd, int msg, IntPtr WP, INTPTR LP); Render the contents of the RichTextBox for Printing//return the last character printed + 1 (printing start from this PO int for next page) public int Print (int charfrom, int. Charto,printpageeventargs e) {//calculate the area to render and Prin Trect rectToPrint; Recttoprint.top = (int) (E.MARGINBOUNDS.TOP * aninch); recttoprint.bottom = (int) (E.marginbounds.bottom * anInch); Recttoprint.left = (int) (E.marginbounds.left * aninch); recttoprint.right = (int) (e.marginbounds.right * anInch);// Calculate the size of the Pagerect rectpage; Rectpage.top = (int) (E.PAGEBOUNDS.TOP * aninch); rectpage.bottom = (int) (E.pagebounds.bottom * aninch); rectpage.left = ( int) (E.pagebounds.left * aninch); recTpage.right = (int) (e.pagebounds.right * aninch); IntPtr hdc = E.GRAPHICS.GETHDC (); FormatRange Fmtrange;fmtrange.chrg.cpmax = charto;//indicate character from to character to FmtRange.chrg.cpMin = Charfro                    M;FMTRANGE.HDC = HDC;              Use the same DC for measuring and renderingfmtrange.hdctarget = HDC;             Point at printer hdcfmtrange.rc = rectToPrint;            Indicate the area in page to Printfmtrange.rcpage = Rectpage; Indicate size of pageintptr res = Intptr.zero;intptr wparam = Intptr.zero;wparam = new IntPtr (1);//get the pointer to th e formatrange structure in memoryintptr lparam= Intptr.zero;lparam = Marshal.alloccotaskmem (marshal.sizeof (FmtRange)); Marshal.structuretoptr (Fmtrange, lparam, false)//send the rendered data for printing res = SendMessage (Handle, Em_format RANGE, wparam, lparam)//free The block of Memory allocatedmarshal.freecotaskmem (lparam);//release the device context Han Dle obtained by a previous calle. GRAPHICS.RELEASEHDC (HDC);//return last + 1 character Printerreturn Res. ToInt32 ();}}}
  6. On the Build menu, click Build Solution to create the RichTextBoxPrintCtrl.dll.
Test controls
  1. Create a new Windows application project in Visual C #. NET. By default, Form1.cs is created.
  2. Drag a button control from the Toolbox into the Form1. Change the Name property to Btnpagesetup, and change the Text property to Page Setup.
  3. Drag another button control from the Toolbox into the Form1. Change the Name property to Btnprintpreview, and change the Text property to print preview.
  4. Drag another button control from the Toolbox into the Form1. Change the Name property to Btnprint, and change the Text property to print.
  5. In the Toolbox, double-click PrintDialog, PrintPreviewDialog, PrintDocument, and PageSetupDialog to add the controls to the Form1.
  6. Modify the Document property of the PrintDialog1, PrintPreviewDialog1, and PageSetupDialog1 controls to PrintDocument1.
  7. On the Tools menu, click Customize Toolbox.
  8. On the. NET Framework Components tab, click Browse, click to select RichTextBoxPrintCtrl.dll, and then click OK.
  9. drag RichTextBoxPrintCtrl from the Toolbox into the Form1.
  10. In Solution Explorer, right-click Form1.cs, and then click View Code.
  11. Add the following code to the  initializecomponent  method:
      This.printDocument1.BeginPrint + = new System.Drawing.Printing.PrintEventHandler (this.printdocument1_ BeginPrint); This.printDocument1.PrintPage + = new System.Drawing.Printing.PrintPageEventHandler ( This.printdocument1_printpage); This.btnPrint.Click + = new System.EventHandler (This.btnprint_click); This.btnPrintPreview.Click + = new System.EventHandler (This.btnprintpreview_click); This.btnPageSetup.Click + = new System.EventHandler (This.btnpagesetup_click);  
  12. Add the following code to the Form1 class:
    private int checkPrint;private void btnPageSetup_Click(object sender, System.EventArgs e){pageSetupDialog1.ShowDialog();}private void btnPrintPreview_Click(object sender, System.EventArgs e){printPreviewDialog1.ShowDialog();}private void btnPrint_Click(object sender, System.EventArgs e){if (printDialog1.ShowDialog() == DialogResult.OK)printDocument1.Print();}private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e){checkPrint = 0;}private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e){// Print the content of RichTextBox. Store the last character printed.checkPrint = richTextBoxPrintCtrl1.Print(checkPrint, richTextBoxPrintCtrl1.TextLength, e);// Check for more pagesif (checkPrint < richTextBoxPrintCtrl1.TextLength)e.HasMorePages = true;elsee.HasMorePages = false;}
  13. On the Debug menu, click Start to run the application. The Form1 will show up.
  14. Type some text in the RichTextBoxPrintCtrl.
  15. Click Page Setup to set the page settings.
  16. Click Print Preview to see a print preview of the page.
  17. Click Print to print the contents of the RichTextBoxPrintCtrl.
For additional information, refer to the following topics in the Microsoft. NET Framework SDK Documentation:
RichTextBox class
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/ Frlrfsystemwindowsformsrichtextboxclasstopic.asp

How to: Print the contents of a RichTextBox control using Visual C #. NET

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.