打印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,还有实现分页打印等

相关推荐
溪水西流8 分钟前
NodifyEditor Zoom 机制分析
开发语言·c#·avalonia
Never_Satisfied3 小时前
在c#中,抛出异常,并指定其message的值
java·javascript·c#
不想看见4045 小时前
Word Ladder Ⅱ -- 广度优先搜索--力扣101算法题解笔记
开发语言·c#
全栈小55 小时前
【C#】.net 6.0和8.0有什么区别,以及8.0增加了那些功能,这些功能有那些作用
开发语言·c#·.net
qq_297908015 小时前
C#印刷线路板ERP进销存报价财务库存贸易生产企业管理系统软件
sqlserver·开源·c#·.net·开源软件
bugcome_com5 小时前
C# 循环语句详解:理解常见循环类型与控制语句
c#
JQLvopkk8 小时前
能用C#开发AI
开发语言·人工智能·c#
游乐码16 小时前
c#类和对象
开发语言·c#
沃码19 小时前
【Lively Wallpaper 】插件开发:LivelyProperties.json 全流程实战教程
c#·json·livelywallpaper·视频壁纸
github.com/starRTC1 天前
Claude Code中英文系列教程34:再谈Skills
开发语言·c#·ai编程