Populate a list with the available printers installed on the local machine

Discussion in 'Win32' started by shabbir, Aug 11, 2005.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    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:
    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];
     
  2. parvez.yu

    parvez.yu New Member

    Joined:
    Feb 14, 2008
    Messages:
    100
    Likes Received:
    0
    Trophy Points:
    0
    thanks for the last explanation of the enumeration of printers
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice