自己很少写技术博客,虽然已经干程序员两年多了,winform开发,web开发都干过,不论项目大小对于.net的相关技术也是了解的,如mvc,wcf,wpf,silverlight,socekt通讯,nhibernate,spring.net wp手机开发等,但是最终发现还是软件架构比所谓的单一功能更为系统化。
下面是一个小的例子 Winfom打印预览
首先是基类DocumentBase继承系统的PrintDocument
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms; namespace prientDemo { public class DocumentBase:PrintDocument { public DialogResult ShowPrintPreviewDialog() { PrintPreviewDialog dialog = new PrintPreviewDialog(); dialog.Document = this; return dialog.ShowDialog(); } } }
然后ImageDocument再继承ImageDocument
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace prientDemo { public class ImageDocument:ImageDocument { private Image _image; public Image Image { get { return _image; } set { _image = value; } } public ImageDocument() { } public ImageDocument(Image image) { this.Image = image; } protected override void OnPrintPage(System.Drawing.Printing.PrintPageEventArgs e) { if(Image==null) { throw new InvalidOperationException(); } e.Graphics.DrawImage(Image, e.MarginBounds); } } }
以上是做打印功能时需要自己写的两个类,
下面是winform窗体的代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace prientDemo { public partial class LoadPicture : Form { public LoadPicture() { InitializeComponent(); } OpenFileDialog pfd = new OpenFileDialog(); private DocumentBase _document; private void Load_Click(object sender, EventArgs e) { if(pfd.ShowDialog(this)==DialogResult.OK){ try { pictureImage.Image = Image.FromFile(pfd.FileName); _document = new ImageDocument(pictureImage.Image); } catch (Exception ex) { MessageBox.Show("This image could not be loaded."+ex.Message); } } } private void Preview_Click(object sender, EventArgs e) { if(_document==null) { MessageBox.Show("You must load an image first"); return; } _document.ShowPrintPreviewDialog(); } } }
下面就完成了,运行效果:如下图