Microsoft KB Archive/176704

{|
 * width="100%"|

HOWTO: Programmatically Share a Printer Under Windows NT

 * }

Q176704

-

The information in this article applies to:


 * Microsoft Win32 Software Development Kit (SDK)
 * Microsoft Windows 2000 Advanced Server
 * Microsoft Windows 2000 Server
 * Microsoft Windows 2000 Professional

-

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 : kbOSWin2000 kbSDKWin32 kbDSupport

Issue type : kbhowto

Technology : kbwin2000AdvServ kbwin2000AdvServSearch kbwin2000Serv kbwin2000Ssearch kbwin2000ProSearch kbwin2000Pro kbWin32SDKSearch kbAudDeveloper kbSDKSearch kbWinAdvServSearch