Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Win32 (http://www.go4expert.com/articles/win32-tutorials/)
-   -   Populate a list with the available printers installed on the local machine (http://www.go4expert.com/articles/populate-list-available-printers-t409/)

shabbir 11Aug2005 09:45

Populate a list with the available printers installed on the local machine
 
There are many occasions where we need to show to the user the list of available printers on the system to choose from and this can be done very easily in MFC with the help of following code snippet

Code: CPP

DWORD dwNeeded = 0, dwItems = 0;
LPBYTE lpPrinterInfo = NULL;
CStringArray szaPrinterArray;
CString szMsg;

::EnumPrinters( PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &dwNeeded, &dwItems );
//Enumerating all the printers available in the system

lpPrinterInfo = new BYTE[dwNeeded];

if(lpPrinterInfo)
{
  //Get the data in the BYTE pointer
  if( EnumPrinters( PRINTER_ENUM_LOCAL, NULL, 2, lpPrinterInfo, dwNeeded,&dwNeeded,&dwItems) )
  {
    for( int i = 0; i< (int)dwItems; i++ )
      //Loop through them and add them to the String Array
      szaPrinterArray.Add((((LPPRINTER_INFO_2)lpPrinterInfo) + i )->pPrinterName);
  }
}
delete lpPrinterInfo;
szMsg = "Printers found on this machine \n";
for(int j=0;j<szaPrinterArray.GetSize();j++)
  szMsg += "\n  " + szaPrinterArray[j];
AfxMessageBox(szMsg);

Code is pretty much self explanatory but then also I would like to make a note as why enumerate the printers twice or more specifically why we call the EnumPrinters API twice.

The reason behind this is we need to know how much bytes of data is needed and that can be retrieved only by Enumerating the printers with 4th Parameters as Null and 5th as 0 and so we just get the dwNeeded as the output parameter which helps us to allocate the buffer of correct size as

Code:

lpPrinterInfo = new BYTE[dwNeeded];

parvez.yu 6Mar2008 15:15

Re: Populate a list with the available printers installed on the local machine
 
thanks for the last explanation of the enumeration of printers


All times are GMT +5.5. The time now is 14:01.