MFC 调用打印机函数

如下代码运行的环境简述:
MFC的对话框界面上创建一个按钮,点击这个按钮打印界面上CListCtrl控件上现实的内容。

void CMaxValueDlg::OnBnClickedButton5()
{
    // TODO: 在此添加控件通知处理程序代码
       // 获取默认电脑默认打印机的名称实现
    CString strPrintDevice;
    TCHAR szBuffer[1024] = { 0 };
    DWORD length = 1024;
    int ret = ::GetDefaultPrinter(szBuffer, &length);
    if (ret == FALSE)
        ret = ::GetLastError(); 
    else
    {
        strPrintDevice=  szBuffer;      
    }

    if (ret == ERROR_INSUFFICIENT_BUFFER)
    {
        CString temp;
        temp.Format(_T("%d"), length);
        AfxMessageBox(CString(_T("ERROR_INSUFFICIENT_BUFFER")) + _T(" the real size is ") + temp);
    }
    else if (ret == ERROR_FILE_NOT_FOUND)
        AfxMessageBox(_T("ERROR_FILE_NOT_FOUND"));
    else
    {
        //CString strRet;
        //strRet.Format(_T("%d"), ret);
        //AfxMessageBox(strRet);
    }


    CString startTm = m_date_s.Format("%Y-%m-%d  %H:%M:%S");
    CString endTm = m_date_e.Format("%Y-%m-%d  %H:%M:%S");
    CString idx;idx.Format("%d", i_id);
    CString wndTm; wndTm.Format("%d", m_UnitWnd);
    CString lockStatus;
    if (m_bNeedLockCheck)
        lockStatus = "有效";
    else
        lockStatus = "无效";
    //this->UpdateData();

    CString strMessage ;
    
    strMessage.AppendFormat("%s \t\t\r\n\r\n\r\n", m_printStr);
    strMessage.AppendFormat("起始日期     %s \t\t\r\n", startTm);
    strMessage.AppendFormat("截止日期     %s \t\t\r\n", endTm);
    strMessage.AppendFormat("单元数据窗   %s \t\t\r\n", idx);
    strMessage.AppendFormat("最大值数量   %s \t\t\r\n", wndTm);
    strMessage.AppendFormat("是否闭锁     %s \t\t\r\n\r\n\r\n\r\n", lockStatus);
    strMessage.Append("序号      极大值      项别       不平衡度       记录时间               是否有效\r\n");
    CString buf[10000][6];
    
    
    int count = c_list.GetItemCount();  
    int colm = c_list.GetHeaderCtrl()->GetItemCount();
    
    for (int i = 0; i < count; i++) {
        
        for (int j = 0; j < colm; j++) {

            buf[i][j] = c_list.GetItemText(i, j);   
        }
        
        strMessage.AppendFormat("%s   %s     %s       %s      %s               %s \r\n", buf[i][0], buf[i][1], buf[i][2], buf[i][3], buf[i][4], buf[i][5]);
        
    }
    

    DWORD dwFlag = PD_ALLPAGES | PD_NOPAGENUMS | PD_USEDEVMODECOPIES | PD_HIDEPRINTTOFILE;  //打印配置界面的按钮可用性,因为后台打印,其实这个配置没什么意义  

    CPrintDialog pPrintdlg(FALSE, dwFlag, this);                                            //CPrintDialog实例化,因为MFC的打印设备无关性,可以理解为这就是一台打印机  

    HGLOBAL hDevMode = NULL;
    HGLOBAL hDevNames = NULL;
    if (GetPrinterDevice(strPrintDevice.GetBuffer(0), &hDevNames, &hDevMode))               //获得指定打印机的配置、名字  
        AfxGetApp()->SelectPrinter(hDevNames, hDevMode);
    else
        AfxMessageBox(_T("Failed to select custom printer"));

    strPrintDevice.ReleaseBuffer();

    pPrintdlg.m_pd.hDevMode = hDevMode;                                                     //让pPrintdlg使用我们指定的打印机  
    pPrintdlg.m_pd.hDevNames = hDevNames;

    CDC dc;
    dc.Attach(pPrintdlg.CreatePrinterDC());                                                 //后台打印创建法,如果需要弹出打印对话框,用DoModal  

    DOCINFO di;                                                                              
    di.cbSize = sizeof(DOCINFO);
    di.lpszDocName = _T("有驱打印测试");
    di.lpszDatatype = NULL;
    di.lpszOutput = NULL;
    di.fwType = 0;

    dc.StartDocA(&di);  
    dc.StartPage();
    dc.SetMapMode(MM_TEXT);

    CRect recPrint(0, 0, dc.GetDeviceCaps(LOGPIXELSX), dc.GetDeviceCaps(LOGPIXELSY));
    dc.DPtoLP(&recPrint);
    dc.SetWindowOrg(0, 0);

    CFont newFont;
    VERIFY(newFont.CreatePointFont(120, _T("宋体"), &dc));
    CFont* oldFont = dc.SelectObject(&newFont);

    dc.SetTextAlign(TA_TOP | TA_LEFT);

    CString strPrint;
    int nIndex = 0;
    int x = 50;
    int y = 50;
    CSize textSize;
    textSize = dc.GetTextExtent(_T("00"), 2);                           //根据当前字体的宽、高,后面以此高度为行高  

    while ((nIndex = strMessage.Find(_T("\r\n"))) > -1)                  //将IDC_EDIT1编辑框中内容打印,支持换行,一次换行等于'\r\n',所以在开头strMessage += _T("\r\n")  
    {
        strPrint = strMessage.Left(nIndex);
        strMessage = strMessage.Mid(nIndex + 2);

        // dc.TextOutW(x, y, strPrint);
        dc.TextOutA(x, y, strPrint);

        y += textSize.cy;                                               //下移一行,行高为字体高度  
    }

    dc.SelectObject(oldFont);
    newFont.DeleteObject();
    dc.EndPage();
    dc.EndDoc();
    DeleteDC(dc.Detach());




}

调用打印机,打印内容


bool CMaxValueDlg::GetPrinterDevice(LPTSTR pszPrinterName, HGLOBAL* phDevNames, HGLOBAL* phDevMode)
{


    //TODO: 在此处添加实现代码.
    //if NULL is passed, then assume we are setting app object's  
    //devmode and devnames  
    if (phDevMode == NULL || phDevNames == NULL)
        return FALSE;

    // Open printer  
    HANDLE hPrinter;
    if (OpenPrinter(pszPrinterName, &hPrinter, NULL) == FALSE)
        return FALSE;

    // obtain PRINTER_INFO_2 structure and close printer  
    DWORD dwBytesReturned, dwBytesNeeded;
    GetPrinter(hPrinter, 2, NULL, 0, &dwBytesNeeded);
    PRINTER_INFO_2* p2 = (PRINTER_INFO_2*)GlobalAlloc(GPTR,
        dwBytesNeeded);
    if (GetPrinter(hPrinter, 2, (LPBYTE)p2, dwBytesNeeded,
        &dwBytesReturned) == 0) {
        GlobalFree(p2);
        ClosePrinter(hPrinter);
        return FALSE;
    }
    ClosePrinter(hPrinter);

    // Allocate a global handle for DEVMODE  
    HGLOBAL  hDevMode = GlobalAlloc(GHND, sizeof(*p2->pDevMode) +
        p2->pDevMode->dmDriverExtra);
    ASSERT(hDevMode);
    DEVMODE* pDevMode = (DEVMODE*)GlobalLock(hDevMode);
    ASSERT(pDevMode);

    // copy DEVMODE data from PRINTER_INFO_2::pDevMode  
    memcpy(pDevMode, p2->pDevMode, sizeof(*p2->pDevMode) +
        p2->pDevMode->dmDriverExtra);
    GlobalUnlock(hDevMode);

    // Compute size of DEVNAMES structure from PRINTER_INFO_2's data  
    DWORD drvNameLen = lstrlen(p2->pDriverName) + 1;  // driver name  
    DWORD ptrNameLen = lstrlen(p2->pPrinterName) + 1; // printer name  
    DWORD porNameLen = lstrlen(p2->pPortName) + 1;    // port name  

    // Allocate a global handle big enough to hold DEVNAMES.  
    HGLOBAL hDevNames = GlobalAlloc(GHND,
        sizeof(DEVNAMES) +
        (drvNameLen + ptrNameLen + porNameLen) * sizeof(TCHAR));
    ASSERT(hDevNames);
    DEVNAMES* pDevNames = (DEVNAMES*)GlobalLock(hDevNames);
    ASSERT(pDevNames);

    // Copy the DEVNAMES information from PRINTER_INFO_2  
    // tcOffset = TCHAR Offset into structure  
    int tcOffset = sizeof(DEVNAMES) / sizeof(TCHAR);
    ASSERT(sizeof(DEVNAMES) == tcOffset * sizeof(TCHAR));

    pDevNames->wDriverOffset = tcOffset;
    memcpy((LPTSTR)pDevNames + tcOffset, p2->pDriverName,
        drvNameLen * sizeof(TCHAR));
    tcOffset += drvNameLen;

    pDevNames->wDeviceOffset = tcOffset;
    memcpy((LPTSTR)pDevNames + tcOffset, p2->pPrinterName,
        ptrNameLen * sizeof(TCHAR));
    tcOffset += ptrNameLen;

    pDevNames->wOutputOffset = tcOffset;
    memcpy((LPTSTR)pDevNames + tcOffset, p2->pPortName,
        porNameLen * sizeof(TCHAR));
    pDevNames->wDefault = 0;

    GlobalUnlock(hDevNames);
    GlobalFree(p2);   // free PRINTER_INFO_2  

    // set the new hDevMode and hDevNames  
    *phDevMode = hDevMode;
    *phDevNames = hDevNames;
    return TRUE;
}

你可能感兴趣的:(MFC 调用打印机函数)