Knowledge Base

How To Programmatically Share a Printer Under Windows NT

Article ID: 176704

Article Last Modified on 2/22/2007


APPLIES TO


This article was previously published under Q176704

SUMMARY

In Windows NT, printers may be shared (or shares removed) using the Win32 SDK API SetPrinter(). The PRINTER_INFO_2 structure contains an Attributes member and a pShareName member that can be used for this purpose. Note that the printer must be opened with administrative permissions for the SetPrinter() call to be successful.

NOTE: On Windows 95 and Windows 98, there is no way to programmatically share a printer.

MORE INFORMATION

The following code demonstrates how to share a printer programmatically on Windows NT:

Sample Code

   BOOL DoSharePrinterNT( LPTSTR szPrinterName, LPTSTR szShareName, BOOL
   bShare )
   {

      HANDLE            hPrinter;
      PRINTER_DEFAULTS   pd;
      DWORD            dwNeeded;
      PRINTER_INFO_2      *pi2;

      // Fill in the PRINTER_DEFAULTS struct to get full permissions.
      ZeroMemory( &pd, sizeof(PRINTER_DEFAULTS) );
      pd.DesiredAccess = PRINTER_ALL_ACCESS;
      if( ! OpenPrinter( szPrinterName, &hPrinter, &pd ) )
      {
         // OpenPrinter() has failed - bail out.
         return FALSE;
      }
      // See how big a PRINTER_INFO_2 structure is.
      if( ! GetPrinter( hPrinter, 2, NULL, 0, &dwNeeded ) )
      {
         if( GetLastError() != ERROR_INSUFFICIENT_BUFFER )
         {
            // GetPrinter() has failed - bail out.
            ClosePrinter( hPrinter );
            return FALSE;
         }
      }
      // Allocate enough memory for a PRINTER_INFO_2 and populate it.
      pi2 = malloc( dwNeeded );
      if( pi2 == NULL )
      {
         // malloc() has failed - bail out.
         ClosePrinter( hPrinter );
         return FALSE;
      }
      if( ! GetPrinter( hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded ) )
      {
         // Second call to GetPrinter() has failed - bail out.
         free( pi2 );
         ClosePrinter( hPrinter );
         return FALSE;
      }
      // We won't mess with the security on the printer.
      pi2->pSecurityDescriptor = NULL;
      // If you want to share the printer, set the bit and the name.
      if( bShare )
      {
         pi2->pShareName = szShareName;
         pi2->Attributes |= PRINTER_ATTRIBUTE_SHARED;
      }
      else // Otherwise, clear the bit.
      {
         pi2->Attributes = pi2->Attributes & (~PRINTER_ATTRIBUTE_SHARED);
      }
      // Make the change.
      if( ! SetPrinter( hPrinter, 2, (LPBYTE)pi2, 0 ) )
      {
         // SetPrinter() has failed - bail out
         free( pi2 );
         ClosePrinter( hPrinter );
         return FALSE;
      }
      // Clean up.
      free( pi2 );
      ClosePrinter( hPrinter );
      return TRUE;
   }
				

Additional query words: share printer network port control panel sharing

Keywords: kbhowto KB176704