zoukankan      html  css  js  c++  java
  • WinForm控件的简单打印方法

    由于项目中使用了大量的用户控件,需要提供打印功能,本人尝试了一种简单的控制打印的方法,基于微软的例子并稍作扩充。
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing.Printing;

    namespace PrintTest
    {
        public partial class UserControl1 : UserControl
        {
            public UserControl1()
            {
                InitializeComponent();
            }       

            private void printDocument2_PrintPage(object sender, PrintPageEventArgs e)
            {
                DoPrint(e);           
            } 
         
            protected Bitmap memoryImage;
            protected virtual void DoPrint(PrintPageEventArgs e)
            {
                float leftMargin = e.MarginBounds.Left;
                float topMargin = e.MarginBounds.Top;
                e.Graphics.DrawImage(memoryImage, leftMargin, topMargin, e.MarginBounds.Width, e.MarginBounds.Height);
            }

            private void CaptureScreen(Control ctrl)
            {
                Size s = ctrl.Size;
                memoryImage = new Bitmap(s.Width, s.Height);
                using (Graphics memoryGraphics = Graphics.FromImage(memoryImage))
                {
                    Rectangle rectClient = new Rectangle(0, 0, s.Width, s.Height);
                    Rectangle rectScreen = this.RectangleToScreen(rectClient);
                    memoryGraphics.CopyFromScreen(rectScreen.Left, rectScreen.Top, 0, 0, s);
                }
            }

            private void btnPrint_Click(object sender, EventArgs e)
            {
                PrintPage();
            }

            public void PrintControl(Control ctrl)
            {
                CaptureScreen(ctrl);
                printDocument2.DefaultPageSettings.Landscape = true;
                printDocument2.Print();
            }

            public virtual void PrintPage()
            {
                PrintControl(this);
            }       
        }
    }
    说明:
    1、在自定义控件中添加了一个“打印”按钮,用于打印控件自己。
    PrintPage 和DoPrint方法声明成虚拟方法是为了在子类中可以重定义,毕竟,作为图片打印不是一个好方法。
    2、对于窗体自身,使用该方法有个问题,那就是窗体通常有标题栏,不同于普通的控件,因此捕捉的图片偏移一个标题栏的大小,如何解决就留给大家了,呵呵。

  • 相关阅读:
    Linux 下的类似Windows下Everything的搜索工具
    windows和linux环境下制作U盘启动盘
    程序调试手段之gdb, vxworks shell
    LeetCode 1021. Remove Outermost Parentheses (删除最外层的括号)
    LeetCode 1047. Remove All Adjacent Duplicates In String (删除字符串中的所有相邻重复项)
    LeetCode 844. Backspace String Compare (比较含退格的字符串)
    LeetCode 860. Lemonade Change (柠檬水找零)
    LeetCode 1221. Split a String in Balanced Strings (分割平衡字符串)
    LeetCode 1046. Last Stone Weight (最后一块石头的重量 )
    LeetCode 746. Min Cost Climbing Stairs (使用最小花费爬楼梯)
  • 原文地址:https://www.cnblogs.com/lotus/p/540677.html
Copyright © 2011-2022 走看看