背景:
在一個 MFC 應用程序中,列出本地系統中安裝的打印機,并檢測是否存在“Microsoft Print to PDF”或“Microsoft XPS Document Writer”虛擬打印機。如果有,則選擇其中一個作為默認或后續操作對象;如果沒有,提示用戶安裝。
實現原理:
#include <afxwin.h> // 包含 MFC 的核心頭文件
#include <winspool.h>
#include <vector>
#include <iostream>void ListPrinters()
{DWORD dwNeeded = 0;DWORD dwReturned = 0;// 獲取所需緩沖區大小if (!EnumPrinters(PRINTER_ENUM_LOCAL, nullptr, 1, nullptr, 0, &dwNeeded, &dwReturned)){if (GetLastError() != ERROR_INSUFFICIENT_BUFFER){std::cerr << "EnumPrinters failed with error code: " << GetLastError() << std::endl;return;}}// 分配緩沖區std::vector<char> buffer(dwNeeded);// 獲取打印機信息PRINTER_INFO_1* pPrinterInfo = reinterpret_cast<PRINTER_INFO_1*>(buffer.data());if (!EnumPrinters(PRINTER_ENUM_LOCAL, nullptr, 1, reinterpret_cast<LPBYTE>(pPrinterInfo), dwNeeded, &dwNeeded, &dwReturned)){std::cerr << "EnumPrinters failed with error code: " << GetLastError() << std::endl;return;}bool hasPdfPrinter = false;bool hasXpsPrinter = false;// 遍歷打印機列表信息for (DWORD i = 0; i < dwReturned; ++i){std::wstring printerName = pPrinterInfo[i].pName;// 檢查是否存在 "Microsoft Print to PDF" 打印機if (printerName == L"Microsoft Print to PDF"){hasPdfPrinter = true;}// 檢查是否存在 "Microsoft XPS Document Writer" 打印機if (printerName == L"Microsoft XPS Document Writer"){hasXpsPrinter = true;}}// 根據存在的打印機情況進行選擇或提示if (hasPdfPrinter){// 如果存在 "Microsoft Print to PDF" 打印機,則選擇它std::wcout << L"Choosing Microsoft Print to PDF..." << std::endl;// 在這里可以執行相應的操作,如將其賦值給 CString 對象等}else if (hasXpsPrinter){// 如果存在 "Microsoft XPS Document Writer" 打印機,則選擇它std::wcout << L"Choosing Microsoft XPS Document Writer..." << std::endl;// 在這里可以執行相應的操作}else{// 如果兩者都不存在,則提示安裝相關軟件std::wcout << L"Neither Microsoft Print to PDF nor Microsoft XPS Document Writer found. Please install the required software." << std::endl;// 在這里可以執行提示用戶安裝軟件的操作}
}// CWinApp 派生類,作為 MFC 應用程序的入口
class CMyApp : public CWinApp
{
public:virtual BOOL InitInstance() override{// 調用 ListPrinters 函數來列舉打印機信息并進行選擇ListPrinters();return TRUE;}
};// 聲明一個 CMyApp 類的實例,作為 MFC 應用程序的入口對象
CMyApp theApp;