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

相关推荐
z落落1 小时前
C# 数组 最终完整版全套笔记(一维+多维+交错+引用类型+对象数组)
java·笔记·c#
weixin_428005304 小时前
.vdproj项目加载提示不兼容问题处理
c#·visual studio·.vdproj·.vdproj不兼容
吴可可1237 小时前
C#显示错误行号的三种方式
c#
魔法阵维护师8 小时前
从零开发游戏需要学习的c#模块,第二十七章(远程攻击 —— 发射子弹)
学习·游戏·c#
weixin_428005308 小时前
C#调用 AI学习从0开始-第1阶段(基础与工具)-第7天多轮对话记忆
人工智能·学习·c#·多轮对话·千问api调用
z落落9 小时前
C# 数组属性和方法(Clear / Copy / IndexOf / LastIndexOf)
开发语言·javascript·c#
光泽雨10 小时前
LINQ 语言集成查询 (Language Integrated Query)
c#·linq
吴可可12310 小时前
C++与C#版Teigha样条离散化差异解析
c++·算法·c#
JaydenAI10 小时前
[MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱(Token)省时间
ai·c#·agent·caching·maf·chatclient中间件
曹牧11 小时前
C#:List<T>.ForEach(Action<T> action)
c#