Introduction
Want to fetch an array of installed printers for use in your WTL apps? Easy - just use this class.
First, include the header:
#include "installedprinters.h"
Next, simply create a CInstalledPrinters
object and the array will be populated automatically. This class is derived from CSimpleArray<CString>
, so you can, for example, fill a listbox using the following code:
CListBox listbox = GetDlgItem(IDC_LIST1);
CInstalledPrinters list;
for (int i = 0; i < list.GetSize(); i++)
listbox.AddString(list[i]);
It's as easy as that, The class will use the Win32 EnumPrinters
API call, using PRINTER_INFO_5
structures - which is probably the fastest way to enumerate printers (no attempt is made to actually open the printer, as this can be slow if you have network printers installed).
CInstalledPrinters
#pragma once
#include <atlmisc.h>
class CInstalledPrinters : public CSimpleArray<CString>
{
public:
CInstalledPrinters(void)
{
GetPrinters();
}
void GetPrinters(void)
{
DWORD dwSize = 0;
DWORD dwPrinters = 0;
if (!::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
NULL, 5, NULL, 0, &dwSize, &dwPrinters))
{
if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return;
}
LPBYTE pBuffer = new BYTE [dwSize];
if (pBuffer == NULL)
return;
if (!::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
NULL, 5, pBuffer, dwSize, &dwSize, &dwPrinters))
{
return;
}
if (dwPrinters == 0)
return;
PRINTER_INFO_5* pInfo = (PRINTER_INFO_5*)pBuffer;
for (DWORD i = 0; i < dwPrinters; i++, pInfo++)
Add(CString(pInfo->pPrinterName));
delete [] pBuffer;
}
};