⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 Winform_理论部分 Wi培训机构的案例的理论部分
💻 CS
字号:
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Printing;

class Script
{
	static public void Main(string[] args)
	{
		//下面代码用于测试
		SimplePrinting printer = new SimplePrinting();
		//printer.PrintFile(@"C:\BOOT.ini", true);
		printer.Print(@"qqqqqqqqq 3333333333 88888888", true);
	}

	public class SimplePrinting 
	{
		public void PrintFile (string filePath, bool preview)
		{
			PrintOut(filePath, true, preview);
		}
		public void Print (string text, bool preview)
		{
			PrintOut(text, false, preview);
		}

		private Font printFont;
		private TextReader streamToPrint;

		// 每页打印前调用此事件
		private void PrintPageRoutine(object sender, PrintPageEventArgs ev) 
		{
			float linesPerPage = 0;
			float yPos =  0;
			int count = 0;
			float leftMargin = ev.MarginBounds.Left;
			float topMargin = ev.MarginBounds.Top;
			string line=null;
            
			//计算每页的行数
			linesPerPage = ev.MarginBounds.Height  / printFont.GetHeight(ev.Graphics) ;

			// 逐行打印
			while (count < linesPerPage && ((line=streamToPrint.ReadLine()) != null)) 
			{
				yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
				ev.Graphics.DrawString (line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
				count++;
			}

			// 还有没有打印内容则另打印一页
			if (line != null) 
				ev.HasMorePages = true;
			else 
				ev.HasMorePages = false;
		}
		private void PrintOut(string data, bool file, bool prview)
		{
			try 
			{
				using (streamToPrint = file ? (TextReader)new StreamReader (data) : (TextReader)new StringReader(data))
				{
					printFont = new Font("Arial", 10);
					PrintDocument pd = new PrintDocument(); 
					pd.PrintPage += new PrintPageEventHandler(PrintPageRoutine);
					if (prview)
					{
						PrintPreviewDialog dlg = new PrintPreviewDialog();
						dlg.Document = pd;
						dlg.ShowDialog();
					}
					else
						pd.Print();
				} 
			} 
			catch(Exception ex) 
			{ 
				MessageBox.Show(ex.Message);
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -