为本地商家处理收据打印机应用。从技术上讲,这是一次重写,我将其视为完整的重构。
原始代码如下所示:
private void btn_print_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
pd.Document = doc;
doc.PrintPage += new PrintPageEventHandler(pd_printpage);
DialogResult res = pd.ShowDialog();
if (res == DialogResult.OK)
{
doc.DefaultPageSettings.Landscape = false;
doc.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Env10", 4, 8);
doc.Print();
}
}
private void pd_printpage(object sender, PrintPageEventArgs e)
{
Graphics gfx = e.Graphics;
SolidBrush blk = new SolidBrush(Color.Black);
Font courier = new Font("Courier New", 12);
Font lucidia = new Font("Lucida Sans", 12);
Font lucidaplus = new Font("Lucida Sans", 18);
StringFormat fmt = new StringFormat(StringFormatFlags.DirectionVertical);
/***** Create Object for Reciept *****/
Recpt rcpt = new Recpt();
rcpt.Contrib = new ContInfo();
rcpt.Pri = new Address();
rcpt.Alt = new Address();
//--- Remainder of function omitted.
这是我目前正在研究的更好的因素版本。
static class Printality
{
private static SolidBrush Blk = new SolidBrush(Color.Black);
private static Font CourierBody = new Font("Courier New", 12);
private static Font LucidaBody = new Font("Lucida Sans", 12);
private static Font LucidaHeader = new Font("Lucida Sans", 18);
private static StringFormat fmt;
public static void PrintReciept(Receipt _rec)
{
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
doc.PrintPage += new PrintPageEventHandler(pd_printPage);
}
private static void pd_printPage(object sender, PrintPageEventArgs e)
{
Graphics gfx = e.Graphics;
fmt = new StringFormat(StringFormatFlags.DirectionVertical);
}
}
最大的问题是:我将一个Receipt对象传递给函数printReceipt()
我该如何将它传递给pd_printPage()
?
答案 0 :(得分:3)
如果我清楚地理解你的问题,你想把参数传递给事件。
doc.PrintPage += (sender, e) => pd_printPage(sender, e, _rec);
private static void pd_printPage(object sender, PrintPageEventArgs e, Receipt rec)
{
Graphics gfx = e.Graphics;
fmt = new StringFormat(StringFormatFlags.DirectionVertical);
}