时间紧迫,直接上代码:
得到电脑的默认打印机
TCHAR szBuffer[1024]={0}; DWORD length = 1024; int ret = ::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); } else if(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) ; const LPPRINTER_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(unsigned int 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);