文章編號: 812425 - 上次校閱: 2007年11月13日 - 版次: 3.4

如何使用 Visual C#.NET 或 Visual C# 2005年列印 RichTextBox 控制項的內容

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。
本文章的有 Microsoft Visual Basic.NET] 版本請參閱 811401? (http://support.microsoft.com/kb/811401/EN-US/ )

在此頁中

全部展開 | 全部摺疊

結論

本文將逐步告訴您,如何列印 RichTextBox 控制項的內容。RichTextBox 控制項並不提供任何方法,以列印該 RichTextBox 內容。您可以擴充 RichTextBox 類別中,以使用 EM_FORMATRANGE 訊息來將 RichTextBox 控制項的內容傳送至一個輸出裝置 (如印表機。

建立 RichTextBoxPrintCtrl 控制項

下列範例說明如何擴充 RichTextBox] 類別,以及如何使用 EM_FORMATRANGE 列印 RichTextBox 控制項的內容。
  1. 在 Visual C#.NET] 或 [Visual C# 2005年建立新的類別庫專案,名為 RichTextBoxPrintCtrl 等。根據預設值,Class1.cs,即建立。
  2. 將 Class1.cs 的名稱變更為 RichTextBoxPrintCtrl.cs。
  3. 在 [方案總管] 中以滑鼠右鍵按一下 [參考],然後按一下 [加入參考]。
  4. 在 [加入參考] 對話方塊連按兩下 System.Drawing.dllSystem.Windows.Forms.dll,],然後再按 [確定]。
  5. Replace the existing code in RichTextBoxPrintCtrl.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 double anInch = 14.4;
    
    		[StructLayout(LayoutKind.Sequential)] 
    			private struct RECT
    		{
    			public int Left;
    			public int Top;
    			public int Right;
    			public int Bottom;
    		}
    
    		[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 IntPtr hdc;             //Actual DC to draw on
    			public IntPtr hdcTarget;       //Target DC for determining text formatting
    			public RECT rc;                //Region of the DC to draw to (in twips)
    			public RECT rcPage;            //Region of the whole 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 point for next page)
    		public int Print( int charFrom, int charTo,PrintPageEventArgs e)
    		{
    			//Calculate the area to render and print
    			RECT 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 page
    			RECT 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 = charFrom;
    			fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
    			fmtRange.hdcTarget = hdc;              //Point at printer hDC
    			fmtRange.rc = rectToPrint;             //Indicate the area on page to print
    			fmtRange.rcPage = rectPage;            //Indicate size of page
    
    			IntPtr res = IntPtr.Zero;
    
    			IntPtr wparam = IntPtr.Zero;
    			wparam = new IntPtr(1);
    
    			//Get the pointer to the FORMATRANGE structure in memory
    			IntPtr lparam= IntPtr.Zero;
    			lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
    			Marshal.StructureToPtr(fmtRange, lparam, false);
    
    			//Send the rendered data for printing 
    			res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);
    
    			//Free the block of memory allocated
    			Marshal.FreeCoTaskMem(lparam);
    
    			//Release the device context handle obtained by a previous call
    			e.Graphics.ReleaseHdc(hdc);
    
    			//Return last + 1 character printer
    			return res.ToInt32();
    		}
    
    	}
    }
  6. 在 [建置] 功能表上按一下 建置方案 建立 RichTextBoxPrintCtrl.dll。

測試控制項

  1. 在 Visual C#.NET] 或 [Visual C# 2005年中建立新的 Windows 應用程式專案。根據預設值,Form1.cs,即建立。

    附註應該在 Visual Studio 2005 中變更程式碼。當您建立 Windows Form 專案時,Visual C# 將一表單加入專案預設。此表單名為 Form1。代表表單的兩個檔案被命名 Form1.cs 和 Form1.designer.cs。您可以撰寫程式碼中 Form1.cs。Designer.cs 檔案是其中 Windows Form 設計工具寫入程式碼會實作所有動作您所加入的控制項執行。 如需有關 Windows Form 設計工具在 Visual C# 2005年中的詳細資訊,請造訪下列 Microsoft 網站]:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx (http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
  2. 從工具箱] 拖曳 [按鈕] 控制項加入 Form1。將 [名稱] 屬性變更為 btnPageSetup,而將 文字 屬性設定為 [版面設定]
  3. 從工具箱] 拖曳 [其他 按鈕] 控制項加入 Form1。將 [名稱] 屬性變更為 btnPrintPreview,而將 Text 屬性設定為 [預覽列印]
  4. 從工具箱] 拖曳 [其他 按鈕] 控制項加入 Form1。將 [名稱] 屬性變更為 btnPrint,而將 Text 屬性設定為 列印
  5. 在工具箱中按兩下 [PrintDialogPrintPreviewDialogPrintDocument,與 PageSetupDialog 若要將這些控制項新增到 Form1]。
  6. 修改 PrintDialog1]、 [PrintPreviewDialog1,] 和 [到 PrintDocument1PageSetupDialog1 控制項的 文件 屬性。
  7. 在 [工具] 功能表上按一下 自訂工具箱
  8. .NET Framework 元件] 索引標籤上按一下 [瀏覽],按一下以選取 RichTextBoxPrintCtrl.dll,然後再按一下 [確定]]。
  9. 從工具箱] 拖曳 [RichTextBoxPrintCtrl 至 Form1。
  10. 在 [方案總管] 中以滑鼠右鍵按一下 [Form1.cs,然後按一下 [檢視程式碼
  11. 將下列程式碼附加至 InitializeComponent 方法:
    		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. 將下列程式碼加入至 Form1 類別:
    		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 pages
    			if (checkPrint < richTextBoxPrintCtrl1.TextLength)
    				e.HasMorePages = true;
    			else
    				e.HasMorePages = false;
    		}
  13. 在 [偵錯] 功能表上按一下 [開始] 執行應用程式]。顯示 [Form1]。
  14. RichTextBoxPrintCtrl 中輸入一些文字。
  15. 按一下 [設定] 頁面設定 版面設定]。
  16. 按一下 [預覽列印] 來檢視頁面的預覽列印。
  17. 按一下 [列印] 以列印 RichTextBoxPrintCtrl 內容]。

?考

如需詳細資訊,請參閱 Microsoft.NET Framework SDK 文件中的下列主題:
RichTextBox 類別
http://msdn2.microsoft.com/en-us/library/system.windows.forms.richtextbox(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.windows.forms.richtextbox(vs.71).aspx)


這篇文章中的資訊適用於:
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2005 Express Edition
關鍵字:?
kbmt kbprint kbwindowsforms kbinheritance kbctrl kbcontrol kbhowtomaster kbhowto KB812425 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:812425? (http://support.microsoft.com/kb/812425/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。