打印是windows的一大特色,打印在我们的生活中很常见,下面,我们用程序实现打印的功能。如果不利于MFC,由Windows应用程序打印一个文档会涉及许多的步骤。首先要获取打印相关的设备描述表。如果已知所用打印机的设备名称,可以调用CreateDC来创建设备描述表:
CDC dc;
dc.CreateDC(NULL,_T("设备名称"),NULL,NULL);
如果不知道设备名称而希望应用程序输出到默认的打印机上。则可以使用MFC中的CPrintDialog::GetDefaults和CPrintDialog::GetPrinterDC函数来创建设备描述表。
CPrintDialog m_printdlg(FALSE);
m_printdlg.DoModal();
CDC pdc;
pdc.Attach(m_printdlg.GetPrinterDC());
一旦获得了打印机DC,就可以准备打印了。下一步是调用StartDoc来标记打印工作的开始。该函数只接受一个参数:指向DOCINFO结标文件名称以及其他与打印工作相关的信息。
接下来就是在打印纸上输出。文本与图形使用GDI函数提交给打印机。如果dc指的是屏幕DC,就会在屏幕上进行处理。如果是打印机的话,就会在打印机上处理。
代码实现:
以上只是稍微的介绍下,具体的请自己查资料。
新建一个对话框工程,添加按钮控件,在对话框类的头文件中,定义变量:
CString str[7];
int screenx,screeny; //窗口每英寸像素数
int printx,printy; //打印机每英寸像素数
double ratex,ratey; //打印机与屏幕的像素比率
CFont font;
在对话框的实现文件中:
void CPrintTextDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
CDC* pDC = GetDC();
screenx = pDC->GetDeviceCaps(LOGPIXELSX);
screeny = pDC->GetDeviceCaps(LOGPIXELSY);
DrawText(pDC,FALSE);
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CPrintTextDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CPrintTextDlg::OnButprint()
{
// TODO: Add your control notification handler code here
DWORD dwflags = PD_PAGENUMS|PD_HIDEPRINTTOFILE|PD_SELECTION|PD_RETURNDEFAULT; //设置打印对话框风格
CPrintDialog dlg(false,dwflags,NULL); //创建打印对话框
if (dlg.DoModal() == IDOK) //是否按钮"打印"按钮
{
CDC dc; //声明设备上下文
dc.Attach(dlg.GetPrinterDC()); //获取打印机DC
int leftmargin;
leftmargin = dc.GetDeviceCaps(PHYSICALOFFSETX);
CRect m_rect(-leftmargin,0,dc.GetDeviceCaps(PHYSICALWIDTH)-leftmargin
,dc.GetDeviceCaps(PHYSICALHEIGHT));
DrawText(&dc,TRUE);
}
}
void CPrintTextDlg::DrawText(CDC *pDC, BOOL IsPrint)
{
if (!IsPrint) //预览
{
ratex = ratey = 1; //当预览时设置比率为1
}
else //判断是打印
{
printx = pDC->GetDeviceCaps(LOGPIXELSX);
printy = pDC->GetDeviceCaps(LOGPIXELSY);
ratex = (double)(printx)/screenx;
ratey = (double)(printy)/screeny;
pDC->StartDoc("printtext"); //开始打印
}
font.CreatePointFont(120,"宋体",pDC); //创建字体
for (int i=0;i<7;i++) //设置循环
{
pDC->SelectObject(&font); //将字体选入设备上下文
pDC->TextOut(int(100*ratex),int(50+i*30*ratey),str[i]); //打印文本
}
if (IsPrint) //判断是打印
{
pDC->EndDoc(); //结束打印
}
font.DeleteObject(); //释放字体
}
HBRUSH CPrintTextDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
CBrush m_brush (RGB(255,255,0));
CRect m_rect;
GetClientRect(m_rect);
pDC->SelectObject(&m_brush);
pDC->FillRect(m_rect,&m_brush);
return m_brush;
}