我们知道,缺省的CFormView类不能打印表单上的控件,本程序试图解决这个问题。
本程序的视窗类CPrintView派生于CFormView,并在其中增加了三个变量用于打印:
CDC * m_pMemDC; //A memory device context compatible with our printer DC.
CRect m_rect; //To hold the dimensions of our printing area while scaling.
CBitmap * m_pBm; //Capture the screen image as a Bitmap
在构造函数中初始化它们: CPrintView::CPrintView() : CFormView(CPrintView::IDD) { m_pMemDC = new CDC ; m_pBm = new CBitmap; //{{AFX_DATA_INIT(CPrintView) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT }
现在,重载CPrintView::OnBeginPrinting(..)函数:
void CPrintView::OnBeginPrinting(CDC* pDC, CPrintInfo* /*pInfo*/) { if (m_pMemDC->GetSafeHdc()) m_pMemDC->DeleteDC(); m_pMemDC->CreateCompatibleDC(pDC); CClientDC dc(this); CRect rect; GetClientRect(rect); m_pMemDC->SetMapMode(MM_ANISOTROPIC); m_pMemDC->SetWindowExt(dc.GetDeviceCaps(LOGPIXELSX),dc.GetDeviceCaps(LOGPIXELSY)); m_pMemDC->SetViewportExt(m_pMemDC->GetDeviceCaps(LOGPIXELSX),m_pMemDC->GetDeviceCaps(LOGPIXELSY)); if (m_pBm->GetSafeHandle()) m_pBm->DeleteObject(); m_pBm->CreateCompatibleBitmap(&dc,rect.Width(),rect.Height()); m_pMemDC->SelectObject(m_pBm); dc.DPtoLP(rect); //Convert to Logical Coordinates m_rect = rect; //Save Logical Coordinates m_pMemDC->BitBlt(0,0,rect.Width(),rect.Height(),&dc,0,0,SRCCOPY); }
下一步,重载CPrintView::OnPrint(..)
void CPrintView::OnPrint(CDC* pDC, CPrintInfo*) { //The Following code scales the image based on printer resolution. pDC->SetMapMode(MM_ANISOTROPIC); pDC->SetWindowExt(m_pMemDC->GetDeviceCaps(LOGPIXELSX),m_pMemDC->GetDeviceCaps(LOGPIXELSY)); pDC->SetViewportExt(pDC->GetDeviceCaps(LOGPIXELSX),pDC->GetDeviceCaps(LOGPIXELSY)); pDC->StretchBlt(0,0,m_rect.Width(),m_rect.Height(),m_pMemDC,0,0,m_rect.Width(),m_rect.Height(),SRCCOPY); }
最后,在析构函数中撤除它们:
CPrintView::~CPrintView() { delete m_pMemDC; //CLEAN UP OUR VARIABLES delete m_pBm; }
>>> DOWN !!! >>>下载源代码及演示程序