从对话框直接打印,而不经过文档/视图类一直是大家竞相探讨的问题。我也找了几份资料,无奈还是不够用。问题是这样的:
我的程序是一个SDI的,但是希望不从主视图打印,而是将打印命令放在一个对话框中。我的想法是最好能够将打印的这套程序放在一个类中,或干脆这个对话框类中实现。不知道可行吗?是的话,该怎么做?请大家不吝赐教!先谢谢啦。

解决方案 »

  1.   

    给一个打印屏幕的代码
    void PreparePrintScreen()
    {
    CDC *pScrDC;
    CWnd *pDeskWnd;
    pDeskWnd=CWnd::FromHandle(GetDesktopWindow());
    pScrDC=pDeskWnd->GetWindowDC();
    if(pPrintMemDC==NULL)
    {
    pPrintMemDC=new CMemDCForPrinting(pScrDC);
    }
    if(pScrDC==NULL)
    {
    AfxMessageBox("::PreparePrintScreen GetDC Fail.");
    return;
    }
    pPrintMemDC->BitBlt(0,0,1024,768,pScrDC,0,0,SRCCOPY);
    pDeskWnd->ReleaseDC(pScrDC);
    }
    void PrintScreen()
    {
    if(pPrintMemDC==NULL)
    return;
    CDC dc;
    int i,j;
    int x,y;
    CPrintDialog PrintDlg(false);
    if(PrintDlg.DoModal()==IDCANCEL)
    return;
    dc.Attach(PrintDlg.GetPrinterDC());
    dc.m_bPrinting=true;

    CString strTitle;
    strTitle.LoadString(AFX_IDS_APP_TITLE); DOCINFO di;
    di.cbSize=sizeof(DOCINFO);
    di.lpszDocName=strTitle;
    di.fwType=0;
    di.lpszOutput=0;
    di.lpszDatatype=0; bool bPrintingOK=dc.StartDoc(&di);
    // dc.SetMapMode(MM_LOENGLISH);
    CPrintInfo Info;
    RECT rect;
    pPrintMemDC->GetClipBox(&rect);
    // Info.m_rectDraw.SetRect(0,0,dc.GetDeviceCaps(HORZRES),dc.GetDeviceCaps(VERTRES));
    x=dc.GetDeviceCaps(HORZRES)/(rect.right-rect.left);
    y=dc.GetDeviceCaps(VERTRES)/(rect.bottom-rect.top);
    Info.m_rectDraw.SetRect(0,0,(rect.right-rect.left)*x,(rect.bottom-rect.top)*y);
    dc.DPtoLP(&Info.m_rectDraw);// for(UINT page = Info.GetMinPage();page<=Info.GetMaxPage()&&bPrintingOK;page++)
    {
    dc.StartPage();
    Info.m_nCurPage=1;
    // pScrDC=GetDC();
    // dc.BitBlt(0,0,1024,768,pDC,0,0,SRCCOPY);
    // dc.SetStretchBltMode(HALFTONE);
    // while(!dc.StretchBlt(0,0,1024*12,768*12,pDC,0,0,1024,768,SRCCOPY));
    // dc.IntersectClipRect(0,0,1024*3,768*3);
    for(i=0;i<(rect.right-rect.left);i++)
    {
    for(j=0;j<(rect.bottom-rect.top);j++)
    {
    COLORREF Color=pPrintMemDC->GetPixel(i,j);
    dc.FillSolidRect(i*x,j*y,x,y,//Color);
    RGB(~GetRValue(Color),~GetGValue(Color),~GetBValue(Color)));
    }
    }
    bPrintingOK=(dc.EndPage()>0);
    }
    if(bPrintingOK)
    {
    dc.EndDoc();
    }
    else
    {
    dc.AbortDoc();
    }
    dc.Detach();
    if(pPrintMemDC!=NULL)
    delete pPrintMemDC;
    pPrintMemDC=NULL;}
    最后先后调用
    这两个函数即可打印当前屏幕
    不过这两函数好象还有点问题如你可改进就告诉我一下