C# 设置打印内容,调用默认打印机直接打印
时间: 2023-12-10 07:51:53 浏览: 222
在 C# 中可以使用 System.Drawing.Printing 命名空间提供的 PrintDocument 类,通过编写 PrintPage 事件处理程序来实现直接打印。下面给出一个示例代码:
```csharp
using System.Drawing;
using System.Drawing.Printing;
// ...
private void PrintText(string text)
{
// 创建 PrintDocument 对象
PrintDocument pd = new PrintDocument();
// 设置 PrintPage 事件处理程序
pd.PrintPage += new PrintPageEventHandler(PrintTextHandler);
// 设置打印机名称
pd.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[0];
// 开始打印
pd.Print();
}
private void PrintTextHandler(object sender, PrintPageEventArgs e)
{
// 获取要打印的文本
string text = "Hello, world!";
// 设置字体和颜色
Font font = new Font("Arial", 12);
Color color = Color.Black;
// 绘制文本
e.Graphics.DrawString(text, font, new SolidBrush(color), 0, 0);
}
```
这个示例代码实现了一个打印文本的函数 PrintText,它接受一个字符串参数 text,将其打印到默认打印机上。PrintText 函数首先创建一个 PrintDocument 对象,设置 PrintPage 事件处理程序为 PrintTextHandler 函数。PrintTextHandler 函数实现了具体的打印操作,将文本绘制到打印页面上。最后,调用 Print 方法开始打印。