1. 程式人生 > >VC/MFC得到電腦的預設印表機、設定預設印表機、遍歷電腦印表機

VC/MFC得到電腦的預設印表機、設定預設印表機、遍歷電腦印表機

http://www.cnblogs.com/zhangdongsheng/archive/2012/08/24/2655090.html

得到電腦的預設印表機、設定預設印表機、遍歷電腦印表機GetDefaultPrinter,SetDefaultPrinter,EnumPrinters

得到電腦的預設印表機

   TCHAR szBuffer[1024]={0};

   DWORD length = 1024;

    intret = ::GetDefaultPrinter(szBuffer,&length);

    if(ret== FALSE)

       ret = ::GetLastError();

    else

    {

       SetDlgItemText(IDC_EDIT1,szBuffer);

       return;

    }

    if(ret == ERROR_INSUFFICIENT_BUFFER)

    {

       CString temp;

       temp.Format(_T("%d"),length);

       AfxMessageBox(CString(_T("ERROR_INSUFFICIENT_BUFFER"))+_T("the real size is ")+temp);

    }

    elseif(ret == ERROR_FILE_NOT_FOUND)

       AfxMessageBox(_T("ERROR_FILE_NOT_FOUND"));

    else

    {

       CString strRet;

       strRet.Format(_T("%d"),ret);

       AfxMessageBox(strRet);

    }

設定電腦預設印表機

   TCHAR szPrinterName[1024]={0};

   GetDlgItemText(IDC_EDIT2,szPrinterName,1024);

   BOOL ret = FALSE;

   ret = SetDefaultPrinter(szPrinterName);

    if(ret== FALSE)

       AfxMessageBox(_T("設定預設印表機失敗"));

    else

        AfxMessageBox(_T("設定預設印表機成功"));

遍歷電腦中的印表機

DWORD Flags = PRINTER_ENUM_FAVORITE |PRINTER_ENUM_LOCAL;

   DWORD cbBuf;

   DWORD pcReturned ;

   CString str;

   DWORD Level = 2;

   TCHAR Name[500]={0} ;

    ::EnumPrinters(Flags,

                   Name,

                   Level,

                   NULL,

                   0,

                   &cbBuf, //需要多少記憶體

                   &pcReturned) ;

    constLPPRINTER_INFO_2 pPrinterEnum = (LPPRINTER_INFO_2)LocalAlloc(LPTR, cbBuf + 4) ;

    if(!pPrinterEnum)

    {

       str.Format(L"error is %d",GetLastError());

       MessageBox(str,0,0);

    }

    if(!EnumPrinters(

       Flags,

       Name,

       Level,

       (LPBYTE)pPrinterEnum,

        cbBuf,

       &cbBuf,

       &pcReturned)

       )

    {

       str.Format(L"error is %d",::GetLastError());

       MessageBox(str,0,0);

       return ;

    }

   CString temp;

   temp.Format(_T("有幾個陣列元素%d"),pcReturned);

    AfxMessageBox(temp);

    for(unsignedint i=0;i<pcReturned;i++)

    {

       m_ListPrinter.InsertItem(i,NULL);      //插入一行

       LPPRINTER_INFO_2 pInfo=&pPrinterEnum[i];

       m_ListPrinter.SetItemText(i,0,pInfo->pPrinterName);

       m_ListPrinter.SetItemText(i,1,pInfo->pServerName);

       m_ListPrinter.SetItemText(i,2,pInfo->pDriverName);

       m_ListPrinter.SetItemText(i,3,pInfo->pPrintProcessor);

    }

   LocalFree(pPrinterEnum);