打印 WinForm 窗体

void DrawForm(Graphics g, int resX, int resY)
{
g.FillRectangle(
new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height);
float scale = resX/ScreenResolution;
foreach (Control c in Controls)
{
string strType = c.GetType().ToString().Substring(c.GetType().ToString().LastIndexOf(".") + 1);
switch (strType)
{
case "Button":
Button b
= (Button)c;
ControlPaint.DrawButton(g, ((Button)c).Left, ((Button)c).Top, ((Button)c).Width, ((Button)c).Height, ButtonState.Normal);
g.DrawString(b.Text, b.Font,
new SolidBrush(b.ForeColor), b.Left + b.Width/2 - g.MeasureString(b.Text, b.Font).Width/2, b.Top  + b.Height/2  - g.MeasureString("a", b.Font).Height/2new StringFormat());
break;
case "TextBox":
TextBox t
= (TextBox)c;
ControlPaint.DrawButton(g, t.Left, t.Top, t.Width, t.Height, ButtonState.Pushed );
g.FillRectangle(
new SolidBrush(t.BackColor), t.Left+1, t.Top + 1, t.Width+2, t.Height -2);
g.DrawString(t.Text, t.Font,
new SolidBrush(t.ForeColor), t.Left + 2, t.Top  + t.Height/2  - g.MeasureString("a", t.Font).Height/2new StringFormat());
break;
case "CheckBox":
CheckBox cb
= (CheckBox)c;
if (cb.Checked)
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height
/2, cb.Height/2, ButtonState.Checked);
else
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height
/2, cb.Height/2, ButtonState.Normal);
g.DrawString(cb.Text, cb.Font,
new SolidBrush(cb.ForeColor), cb.Right -cb.Height - g.MeasureString(cb.Text, cb.Font).Width , cb.Top,  new StringFormat());
break;
}

}

}

private void printDocument1_PrintPage( object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterResolution pr
= e.PageSettings.PrinterResolution;
DrawForm(e.Graphics, pr.X, pr.Y);
}

float ScreenResolution = 96.0f ;
private void Form1_Paint( object sender, System.Windows.Forms.PaintEventArgs e)
{
ScreenResolution
= e.Graphics.DpiX;
}

添加以上几个事件。
在窗体上添加如下控件:
private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
private System.Drawing.Printing.PrintDocument printDocument1;
其中,窗口上要添加它的Paint事件也就是上面的Form1_Paint,printDocument1要添加它的PrintPage事件,也就是上面的printDocument1_PrintPage事件
然后的话,用菜单或按钮调用printDocument1.Print();
就可以进行打印了。也可以直接调用printPreviewDialog1.ShowDialog()事件就可以进行打印预览。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值