WTL 已安装打印机列表





5.00/5 (2投票s)
2002年11月8日

76426

1674
在您的 WTL 应用程序中使用此类来检索已安装打印机列表。
引言
想在你的 WTL 应用中使用已安装打印机的数组吗?很简单 - 只需要使用这个类。
首先,包含头文件
#include "installedprinters.h"
接下来,简单地创建一个 CInstalledPrinters
对象,数组就会自动填充。这个类是从 CSimpleArray<CString>
派生的,所以你可以,例如,使用以下代码填充一个列表框
CListBox listbox = GetDlgItem(IDC_LIST1); // Get the list of installed printers CInstalledPrinters list; // Fill listbox for (int i = 0; i < list.GetSize(); i++) listbox.AddString(list[i]);
就是这么简单。该类将使用 Win32 EnumPrinters
API 调用,使用 PRINTER_INFO_5
结构 - 这可能是枚举打印机最快的方法(不会尝试实际打开打印机,因为如果安装了网络打印机,这可能会很慢)。
CInstalledPrinters
#pragma once #include <atlmisc.h> class CInstalledPrinters : public CSimpleArray<CString> { public: CInstalledPrinters(void) { GetPrinters(); } void GetPrinters(void) { DWORD dwSize = 0; DWORD dwPrinters = 0; // Enumerate all installed printers if (!::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 5, NULL, 0, &dwSize, &dwPrinters)) { // Check for ERROR_INSUFFICIENT_BUFFER // If something else, then quit if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER) return; // Fall through } // Allocate some buffer memory LPBYTE pBuffer = new BYTE [dwSize]; if (pBuffer == NULL) return; // Fill the buffer // Again, this depends on the O/S if (!::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS, NULL, 5, pBuffer, dwSize, &dwSize, &dwPrinters)) { // Error - unlikely though // as first call to EnumPrinters // succeeded! return; } // Do we have any printers? if (dwPrinters == 0) return; // Cast to PRINTER_INFO_2 PRINTER_INFO_5* pInfo = (PRINTER_INFO_5*)pBuffer; // Loop adding the printers to the list for (DWORD i = 0; i < dwPrinters; i++, pInfo++) Add(CString(pInfo->pPrinterName)); delete [] pBuffer; } };