• Vui lòng đọc nội qui diễn đàn để tránh bị xóa bài viết
  • Tìm kiếm trước khi đặt câu hỏi

In trong RichTextBox

Các thủ thuật liên quan đến ứng dụng, biểu mẫu và control

Điều hành viên: tungcan5diop, QUANITGROBEST

Đặng Việt Trung
Thành viên chính thức
Thành viên chính thức
Bài viết: 19
Ngày tham gia: T.Ba 13/06/2006 5:26 pm
Đến từ: Hà Nội
Liên hệ:

In trong RichTextBox

Gửi bàigửi bởi Đặng Việt Trung » T.Bảy 29/03/2008 1:17 pm

Thủ thuật: In trong RichTextBox
Tác giả: MSDN
Mô tả: In trong RichTextBox


Tạo 1 usercontrol mới rồi cho đoạn code sau vào rồi build

Mã: Chọn hết

  1. Option Explicit On
  2.  
  3. Imports System
  4. Imports System.Windows.Forms
  5. Imports System.Drawing
  6. Imports System.Runtime.InteropServices
  7. Imports System.Drawing.Printing
  8.  
  9. Namespace RichTextBoxPrintCtrl
  10.    Public Class RichTextBoxPrintCtrl
  11.       Inherits RichTextBox
  12.       ' Convert the unit that is used by the .NET framework (1/100 inch)
  13.       ' and the unit that is used by Win32 API calls (twips 1/1440 inch)
  14.       Private Const AnInch As Double = 14.4
  15.  
  16.       <StructLayout(LayoutKind.Sequential)> _
  17.        Private Structure RECT
  18.          Public Left As Integer
  19.          Public Top As Integer
  20.          Public Right As Integer
  21.          Public Bottom As Integer
  22.       End Structure
  23.  
  24.       <StructLayout(LayoutKind.Sequential)> _
  25.       Private Structure CHARRANGE
  26.          Public cpMin As Integer          ' First character of range (0 for start of doc)
  27.          Public cpMax As Integer          ' Last character of range (-1 for end of doc)
  28.       End Structure
  29.  
  30.       <StructLayout(LayoutKind.Sequential)> _
  31.       Private Structure FORMATRANGE
  32.          Public hdc As IntPtr             ' Actual DC to draw on
  33.          Public hdcTarget As IntPtr       ' Target DC for determining text formatting
  34.          Public rc As Rect                ' Region of the DC to draw to (in twips)
  35.          Public rcPage As Rect            ' Region of the whole DC (page size) (in twips)
  36.          Public chrg As CHARRANGE         ' Range of text to draw (see above declaration)
  37.       End Structure
  38.  
  39.       Private Const WM_USER As Integer = &H400
  40.       Private Const EM_FORMATRANGE As Integer = WM_USER + 57
  41.  
  42.       Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wp As IntPtr, ByVal lp As IntPtr) As IntPtr
  43.  
  44.       ' Render the contents of the RichTextBox for printing
  45.       ' Return the last character printed + 1 (printing start from this point for next page)
  46.       Public Function Print(ByVal charFrom As Integer, ByVal charTo As Integer, ByVal e As PrintPageEventArgs) As Integer
  47.  
  48.          ' Mark starting and ending character
  49.          Dim cRange As CHARRANGE
  50.          cRange.cpMin = charFrom
  51.          cRange.cpMax = charTo
  52.  
  53.          ' Calculate the area to render and print
  54.          Dim rectToPrint As RECT
  55.          rectToPrint.Top = e.MarginBounds.Top * AnInch
  56.          rectToPrint.Bottom = e.MarginBounds.Bottom * AnInch
  57.          rectToPrint.Left = e.MarginBounds.Left * AnInch
  58.          rectToPrint.Right = e.MarginBounds.Right * AnInch
  59.  
  60.          ' Calculate the size of the page
  61.          Dim rectPage As RECT
  62.          rectPage.Top = e.PageBounds.Top * AnInch
  63.          rectPage.Bottom = e.PageBounds.Bottom * AnInch
  64.          rectPage.Left = e.PageBounds.Left * AnInch
  65.          rectPage.Right = e.PageBounds.Right * AnInch
  66.  
  67.          Dim hdc As IntPtr = e.Graphics.GetHdc()
  68.  
  69.          Dim fmtRange As FORMATRANGE
  70.          fmtRange.chrg = cRange                 ' Indicate character from to character to
  71.          fmtRange.hdc = hdc                     ' Use the same DC for measuring and rendering
  72.          fmtRange.hdcTarget = hdc               ' Point at printer hDC
  73.          fmtRange.rc = rectToPrint              ' Indicate the area on page to print
  74.          fmtRange.rcPage = rectPage             ' Indicate whole size of page
  75.  
  76.          Dim res As IntPtr = IntPtr.Zero          
  77.  
  78.          Dim wparam As IntPtr = IntPtr.Zero
  79.          wparam = New IntPtr(1)
  80.  
  81.          ' Move the pointer to the FORMATRANGE structure in memory
  82.          Dim lparam As IntPtr = IntPtr.Zero
  83.          lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange))
  84.          Marshal.StructureToPtr(fmtRange, lparam, False)
  85.  
  86.          ' Send the rendered data for printing
  87.          res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam)
  88.  
  89.          ' Free the block of memory allocated
  90.          Marshal.FreeCoTaskMem(lparam)
  91.  
  92.          ' Release the device context handle obtained by a previous call
  93.          e.Graphics.ReleaseHdc(hdc)
  94.  
  95.          ' Return last + 1 character printer
  96.          Return res.ToInt32()
  97.       End Function
  98.  
  99.    End Class
  100. End Namespace


Mã: Chọn hết

  1. using System;
  2. using System.Windows.Forms;
  3. using System.Drawing;
  4. using System.Runtime.InteropServices;
  5. using System.Drawing.Printing;
  6.  
  7. namespace RichTextBoxPrintCtrl
  8. {
  9.     public class RichTextBoxPrintCtrl:RichTextBox
  10.     {
  11.         //Convert the unit used by the .NET framework (1/100 inch)
  12.         //and the unit used by Win32 API calls (twips 1/1440 inch)
  13.         private const double anInch = 14.4;
  14.  
  15.         [StructLayout(LayoutKind.Sequential)]
  16.             private struct RECT
  17.         {
  18.             public int Left;
  19.             public int Top;
  20.             public int Right;
  21.             public int Bottom;
  22.         }
  23.  
  24.         [StructLayout(LayoutKind.Sequential)]
  25.             private struct CHARRANGE
  26.         {
  27.             public int cpMin;         //First character of range (0 for start of doc)
  28.             public int cpMax;           //Last character of range (-1 for end of doc)
  29.         }
  30.  
  31.         [StructLayout(LayoutKind.Sequential)]
  32.             private struct FORMATRANGE
  33.         {
  34.             public IntPtr hdc;             //Actual DC to draw on
  35.             public IntPtr hdcTarget;       //Target DC for determining text formatting
  36.             public RECT rc;                //Region of the DC to draw to (in twips)
  37.             public RECT rcPage;            //Region of the whole DC (page size) (in twips)
  38.             public CHARRANGE chrg;         //Range of text to draw (see earlier declaration)
  39.         }
  40.  
  41.         private const int WM_USER  = 0x0400;
  42.         private const int EM_FORMATRANGE  = WM_USER + 57;
  43.        
  44.         [DllImport("USER32.dll")]
  45.         private static extern IntPtr SendMessage (IntPtr hWnd , int msg , IntPtr wp, IntPtr lp);
  46.  
  47.         // Render the contents of the RichTextBox for printing
  48.         //  Return the last character printed + 1 (printing start from this point for next page)
  49.         public int Print( int charFrom, int charTo,PrintPageEventArgs e)
  50.         {
  51.             //Calculate the area to render and print
  52.             RECT rectToPrint;
  53.             rectToPrint.Top = (int)(e.MarginBounds.Top * anInch);
  54.             rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * anInch);
  55.             rectToPrint.Left = (int)(e.MarginBounds.Left * anInch);
  56.             rectToPrint.Right = (int)(e.MarginBounds.Right * anInch);
  57.  
  58.             //Calculate the size of the page
  59.             RECT rectPage;
  60.             rectPage.Top = (int)(e.PageBounds.Top * anInch);
  61.             rectPage.Bottom = (int)(e.PageBounds.Bottom * anInch);
  62.             rectPage.Left = (int)(e.PageBounds.Left * anInch);
  63.             rectPage.Right = (int)(e.PageBounds.Right * anInch);
  64.  
  65.             IntPtr hdc = e.Graphics.GetHdc();
  66.  
  67.             FORMATRANGE fmtRange;
  68.             fmtRange.chrg.cpMax = charTo;               //Indicate character from to character to
  69.             fmtRange.chrg.cpMin = charFrom;
  70.             fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
  71.             fmtRange.hdcTarget = hdc;              //Point at printer hDC
  72.             fmtRange.rc = rectToPrint;             //Indicate the area on page to print
  73.             fmtRange.rcPage = rectPage;            //Indicate size of page
  74.  
  75.             IntPtr res = IntPtr.Zero;
  76.  
  77.             IntPtr wparam = IntPtr.Zero;
  78.             wparam = new IntPtr(1);
  79.  
  80.             //Get the pointer to the FORMATRANGE structure in memory
  81.             IntPtr lparam= IntPtr.Zero;
  82.             lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
  83.             Marshal.StructureToPtr(fmtRange, lparam, false);
  84.  
  85.             //Send the rendered data for printing
  86.             res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);
  87.  
  88.             //Free the block of memory allocated
  89.             Marshal.FreeCoTaskMem(lparam);
  90.  
  91.             //Release the device context handle obtained by a previous call
  92.             e.Graphics.ReleaseHdc(hdc);
  93.  
  94.             //Return last + 1 character printer
  95.             return res.ToInt32();
  96.         }
  97.  
  98.     }
  99. }
  100.  
  101.  
  102.  


Thêm control printDocument vào Form và btnPrint, btnPrintPreview, btnPageSetup và control vừa tạo vào form. Thêm vào phần InitializeComponent :

Mã: Chọn hết

  1. this.printDocument1.BeginPrint += new System.Drawing.Printing.PrintEventHandler(this.printDocument1_BeginPrint);
  2.         this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
  3.         this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
  4.         this.btnPrintPreview.Click += new System.EventHandler(this.btnPrintPreview_Click);
  5.         this.btnPageSetup.Click += new System.EventHandler(this.btnPageSetup_Click);

Thêm đoạn này vào Form. Đặt sự kiện cho các button

Mã: Chọn hết

  1. private int checkPrint;
  2.         private void btnPageSetup_Click(object sender, System.EventArgs e)
  3.         {
  4.             pageSetupDialog1.ShowDialog();
  5.         }
  6.  
  7.         private void btnPrintPreview_Click(object sender, System.EventArgs e)
  8.         {
  9.             printPreviewDialog1.ShowDialog();
  10.         }
  11.  
  12.         private void btnPrint_Click(object sender, System.EventArgs e)
  13.         {
  14.             if (printDialog1.ShowDialog() == DialogResult.OK)
  15.                 printDocument1.Print();
  16.         }
  17.  
  18.         private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
  19.         {
  20.             checkPrint = 0;
  21.         }
  22.  
  23.         private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
  24.         {
  25.             // Print the content of RichTextBox. Store the last character printed.
  26.             checkPrint = richTextBoxPrintCtrl1.Print(checkPrint, richTextBoxPrintCtrl1.TextLength, e);
  27.  
  28.             // Check for more pages
  29.             if (checkPrint < richTextBoxPrintCtrl1.TextLength)
  30.                 e.HasMorePages = true;
  31.             else
  32.                 e.HasMorePages = false;
  33.         }

// ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.KB.v10.en/enu_kbvcsharpnetkb/vcsharpnetkb/812425.htm



tanbinh25
Bài viết: 2
Ngày tham gia: T.Tư 20/06/2012 7:57 am

Re: In trong RichTextBox

Gửi bàigửi bởi tanbinh25 » T.Sáu 12/10/2012 12:04 am

Anh ơi cho em hoi tí. Đây là đoạn code in richtextBox, sao em không thấy chổ nào để mình điền cái richtextbox của mình muốn in gì hết vậy. em moi học có gì mấy anh chi bảo thêm.
Thân.


Quay về “[.NET] Ứng dụng - Form và Control”

Đang trực tuyến

Đang xem chuyên mục này: Không có thành viên nào trực tuyến.1 khách