不用DOC/VIEW类结构进行打印

类别:VC语言 点击:0 评论:0 推荐:
直接打印,不需要文档/视

闻怡洋 译 [email protected] http://vchelp.163.net

This article was contributed by Chris Maunder.

如果你需要在没有使用文档/视图的应用中使用打印功能(比如说在对话框中)你将无法利用MFC提供的功能,而且对于某些新手来讲有些困难。 下面的的代码可以供你在对话框中如果在DOC/View中一样使用打印功能。你必须定义OnBeginPrinting, OnEndPrinting 和 OnPrint三个函数,其原型和功能与在VIEW中一样。


void CMyDialog::Print()
{
CDC dc;
CPrintDialog printDlg(FALSE);
//利用CPrintDialog 生成打印机设备环境
if (printDlg.DoModal() == IDCANCEL) // Get printer settings from user 让用户选择打印纸张等
return;

dc.Attach(printDlg.GetPrinterDC()); // Attach a printer DC 让HANDLE连接到dc上
dc.m_bPrinting = TRUE;

CString strTitle; // Get the application title ?
strTitle.LoadString(AFX_IDS_APP_TITLE);

DOCINFO di; // Initialise print document details DOCINFO中有相关的打印信息
::ZeroMemory (&di, sizeof (DOCINFO));
di.cbSize = sizeof (DOCINFO);
di.lpszDocName = strTitle;//设置标题

BOOL bPrintingOK = dc.StartDoc(&di); // Begin a new print job 开始打印

// Get the printing extents and store in the m_rectDraw field of a
// CPrintInfo object
CPrintInfo Info;//
Info.m_rectDraw.SetRect(0,0,
dc.GetDeviceCaps(HORZRES),
dc.GetDeviceCaps(VERTRES));//设置范围

OnBeginPrinting(&dc, &Info); // 调用你自己定义的初始化功能
for (UINT page = Info.GetMinPage(); page<Info.GetMaxPage()&& bPrintOK;page++)
{Info.m_nCurPage = page;
OnPrint(&dc, &Info); // Call your "Print page" function
bPrintingOK = (dc.EndPage() > 0); // end page
}
OnEndPrinting(&dc, &Info); // 结束打印

if (bPrintingOK)
dc.EndDoc(); // end a print job
else
dc.AbortDoc(); // abort job.

dc.Detach(); // detach the printer DC
}

[译者:其实在WINDOWS环境中是设备无关的。只要有了DC,你可以使用各种GDI函数,而不需要理会是在屏幕或是在打印机上绘图。在Windows3.X一般使用CreateDC创建打印环境,在WIN32下好象并不是很兼容,使用CPrintDialog产生打印DC是个不错的方法。你只要看看MFC的源代码就能搞清楚PrintDialog是怎么产生DC的了。 蓝色的代码是讲诉如何初始化打印的参数,而其他的参数你可以在OnBeginPrint中进行设置]

本文地址:http://com.8s8s.com/it/it3970.htm