HOWTO: Programmatically Share a Printer Under Windows NT

ID: Q176704


The information in this article applies to:


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;
      }
      // 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          : kbSDKWin32 kbDSupport 
Version           : WINDOWS:
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: June 30, 1999