打印Winfrom控件实现简陋版的打印(C#)

本文在前面写的博文基础上进行修改:利用Graphics的CopyFromScreen实现简陋版的打印(C#)_zxy2847225301的博客-CSDN博客

通过截图的方式进行打印在前面的文章后面已经介绍过,有问题。

UI布局如下:

代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace winformDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
            this.button1.Click += new System.EventHandler(this.button1_Click);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            PrintToGraphics(e.Graphics, e.MarginBounds);
        }
        public void PrintToGraphics(Graphics graphics, Rectangle bounds)
        {
            Bitmap bitmap = new Bitmap(this.Width, this.Height);
            this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
            Rectangle target = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            graphics.PageUnit = GraphicsUnit.Display;
            graphics.DrawImage(bitmap, target);
           
        }
    }
}

运行结果如下:

把Form1窗体往任务栏方向挪动,不会出现前面博文中说的那个问题,如下图:

好了,本水文到此结束。后面还有继续深入研究的,如打印单个控件TextBox,Button,还有实现分页打印等

相关推荐
xiaogutou11211 小时前
2026年历史课件PPT模板选购指南:教师备课效率与精度的平衡方案
开发语言·c#
Eiceblue4 小时前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel
不会编程的懒洋洋6 小时前
WPF XAML+布局+控件
xml·开发语言·c#·视觉检测·wpf·机器视觉·视图
唐青枫6 小时前
别再层层传参了!C#.NET AsyncLocal 异步上下文透传实战
c#·.net
明如正午8 小时前
【C#】托管调试助手 “PInvokeStackImbalance“:的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。
c#
Eiceblue8 小时前
C# 如何实现 Word 转 Excel ?分享两种实用方法
c#·word·excel
天才少女爱迪生8 小时前
word格式规范检测+自动修改【python】
python·c#·word
用户3721574261359 小时前
如何使用 C# 转换 PowerPoint 为 HTML:完整指南
c#
软泡芙9 小时前
【C# 】各种等待大全:从入门到精通
开发语言·c#·log4j
夏霞10 小时前
IIS 应用程序池 3 种标识:ApplicationPoolIdentity / LocalSystem / LocalService 权限区别(超清晰)
c#·.net