WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Tutorials
plus

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Printing

 Keywords: Printer Extender WIL Print Function WMI Win32_Printer PrnAdmin shimgvw.dll ImageView_PrintTo

Contents


Printer Extender

The Printer Extender allows you to access and manipulate printer information. The functions are useful for getting and setting the default printer. Here is a Complete Function List:

	pAddPrinter
	Adds a printer to the list of supported printers for a server.
	
	pAddPrtConn
	Adds a connection to a printer for the current user.
	
	pDelPrinter
	Removes an installed printer.
	
	PDelPrtConn
	Removes a connection to a printer.
	
	pGetDefPrtInf
	Get info on default printer.
	
	pGetErrorCode
	Get extended error code.
	
	pGetErrorMsg
	Get extended error message.
	
	pGetPrtAttrib
	Get printer attribute.
	
	pGetPrtInfo
	Gets information about a printer.
	
	pGetPrtList
	Get printer list
	
	pPaperBins
	Returns a list of available paper bins.
	
	pPaperSizes
	Returns a list of paper sizes.
	
	pSetDefPrt
	Set default printer.
	
	pSetDefPrtEx
	Set default printer (extended).
	
	pSetPrtAttrib
	Set printer attribute.
	
	pSetPrtInfo
	Sets information about a printer.
	
	pVersionInfo
	Returns information on this extender.
	


WIL Print Function

The WIL Print function instructs the application responsible for a file to print the file on the default printer. The Windows ShellExecute API is used. It examines the extension of the data file, looks the extension up in the Windows registry to determine the owning application, starts the owning application, and instructs it, also according to data specified in the registry, to print the data file. Most applications will send the printout to the default printer, however the exact action taken by the application is under the application’s own control.

Applications that support this command or their setup programs will generally make the necessary modifications to the Windows registry to allow this function to perform successfully.

Example:

	FileCopy("C:\config.sys", "xxx.txt", 0)
	   a=Print("xxx.txt", DirGet( ), @NORMAL, 0)
	   FileDelete("xxx.txt")
	


Printer Commandline Tricks

Windows provides several utilities to help you administer your network printing resources.

rundll32

Some enterprise configurations require clients to connect to network printers during an unattended setup. Microsoft facilitates this with the rundll32 command, which allows printers to be installed from the command line. This is particularly useful when you need to add or remove printers from a group of users by means of a logon script.

The rundll32 command provides greater control than older supplemental utilities such as Con2prt.exe, which allowed only for the addition and deletion of networked printers. For example, the rundll32 command allows local printers to be modified and deleted. It also allows you to add printer connections by computer rather than by user as the Add Printer Wizard does. The result is that you can control all aspects of the end user's printing experience by running a local or remote WinBatch script or logon script containing rundll32 commands.

The case-sensitive syntax for the rundll32 command is:

rundll32 printui.dll,PrintUIEntry <options> 

Examples of useful options include:

	; This installs a printer for the user logged on a remote computer named computer
	; by running the Add Printer Wizard.
	Run("rundll32.exe", "printui.dll,PrintUIEntry /il /c\\computer")
	
	; This adds a connection to print_server/printer for all users on a remote computer named computer.
	Run("rundll32.exe", "printui.dll,PrintUIEntry /ga /c\\computer /n\\print_server\printer")
	

Here is a list of PrintUIEntry commandline switches:

	rundll32 printui.dll,PrintUIEntry [options] [@commandfile]
   /a[file] binary file name
   /b[name] base printer name
   /c[name] unc machine name if the action is on a remote machine
   /dl delete local printer
   /dn delete network printer connection
   /dd delete printer driver
   /e display printing preferences
   /f[file] either inf file or output file
   /ga add per machine printer connections
   /ge enum per machine printer connections
   /gd delete per machine printer connections
   /h[arch] driver architecture one of the following, Alpha | Intel | IA64 | x64
   /ia install printer driver using inf file
   /id install printer driver using add printer driver wizard
   /if install printer using inf file
   /ii install printer using add printer wizard with an inf file
   /il install printer using add printer wizard
   /in add network printer connection
   /j[provider] print provider name
   /k print test page to specified printer, cannot be combined with command when installing a printer
   /l[path] printer driver source path
   /m[model] printer driver model name
   /n[name] printer name
   /o display printer queue view
   /p display printer properties
   /q quiet mode, do not display error messages
   /r[port] port name
   /s display server properties
   /Ss Store printer settings into a file
   /Sr Restore printer settings from a file
   Store or restore printer settings option flags that must be placed at the end of command:
	2	PRINTER_INFO_2
	7	PRINTER_INFO_7
	c	Color Profile
	d	PrinterData
	s	Security descriptor
	g	Global DevMode
	m	Minimal settings
	u	User DevMode
	r	Resolve name conflicts
	f	Force name
	p	Resolve port
   /u use the existing printer driver if it's already installed
   /t[#] zero based index page to start on
   /v[version] driver version one of the following, Windows 95, 98 and Me | Windows NT 4.0 | Windows NT 4.0 or 2000 | Windows 2000 or XP | Windows XP
   /w prompt the user for a driver if specified driver is not found in the inf
   /y set printer as the default
   /Xg get printer settings
   /Xs set printer settings
   /z do not auto share this printer
   /Y do not auto generate a printer name
   /K changes the meaning of /v and /h to accept 0,1,2,3, respectively for Windows x64 and Windows IA64 | Windows NT x86 | Windows NT Alpha_AXP | Windows 4.0
   /Z share this printer, can only be used with the /if option
   /? help this message
   @[file] command line argument file
   /Mw[message] show a warning message before committing the command
   /Mq[message] show a confirmation message before committing the command
   /W[flags] specifies flags and switches for the wizards (for APW & APDW)
	r	make the wizards to be restart-able from the last page
   /G[flags] specifies global flags and switches
	w	suppress setup driver warnings UI (super quiet mode)
	
Here are some examples of what you can do:
	   ; Run server properties:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /s /t1 /n\\machine')
	
	   ;Run printer properties:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /p /n\\machine\printer')
	
	   ;Run add printer wizard localy:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /il')
	
	   ;Run add printer wizard on \\machine:
	   Run('rundll32.exe', 'rundll32 printui.dll,PrintUIEntry /il /c\\machine')
	
	   ;Run queue view:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /o /n\\machine\printer')
	
	   ;Run inf install:
	   Run('rundll32.exe', StrCat('printui.dll,PrintUIEntry /if /b "Test Printer" /f ', DirWindows(2),'inf\ntprint.inf /r "lpt1:" /m "AGFA-AccuSet v52.3"'))
	
	   ;Run add printer wizard using inf:
	   Run('rundll32.exe', StrCat('printui.dll,PrintUIEntry /ii /f ', DirWindows(2), 'inf\ntprint.inf'))
	
	   ;Add per machine printer connection:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /ga /c\\machine /n\\machine\printer /j"LanMan Print Services"')
	
	   ;Delete per machine printer connection:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /gd /c\\machine /n\\machine\printer')
	
	   ;Enumerate per machine printer connections:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /ge /c\\machine')
	
	   ;Add printer driver using inf:
	   Run('rundll32.exe', StrCat('printui.dll,PrintUIEntry /ia /c\\machine /m "AGFA-AccuSet v52.3" /h "Intel" /v "Windows 2000 or XP" /f ', DirWindows(2),'inf\ntprint.inf'))
	
	   ;Add printer driver using inf:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /ia /K /c\\machine /m "AGFA-AccuSet v52.3" /h "Windows NT x86" /v 3')
	
	   ;Remove printer driver:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /dd /c\\machine /m "AGFA-AccuSet v52.3" /h "Intel" /v "Windows 2000 or XP"')
	
	   ;Remove printer driver:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /dd /K /c\\machine /m "AGFA-AccuSet v52.3" /h "Windows NT x86" /v 3')
	
	   ;Set printer as default:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /y /n "printer"')
	
	   ;Set printer comment:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Xs /n "printer" comment "My Cool Printer"')
	
	   ;Get printer settings:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Xg /n "printer"')
	
	   ;Get printer settings saving results in a file:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /f "results.txt" /Xg /n "printer"')
	
	   ;Set printer settings command usage:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Xs /n "printer" ?')
	
	   ;Store all printer settings into a file:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Ss /n "printer" /a "file.dat"')
	
	   ;Restore all printer settings from a file:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Sr /n "printer" /a "file.dat"')
	
	   ;Store printer information on level 2 into a file :
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Ss /n "printer" /a "file.dat" 2')
	
	   ;Restore  from a file printer security descriptor:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Sr /n "printer" /a "file.dat" s')
	
	   ;Restore  from a file printer global devmode and printer data:
	   rRun('rundll32.exe', 'printui.dll,PrintUIEntry /Sr /n "printer" /a "file.dat" g d')
	
	   ;Restore  from a file minimum settings and resolve port name:
	   Run('rundll32.exe', 'printui.dll,PrintUIEntry /Sr /n "printer" /a "file.dat" m p')
	
Automate printing a test page.

	params = StrCat("PRINTUI.DLL,PrintUIEntry /p /n ", '"', printerName,'"')
	   Run ("RUNDLL32.exe", params)
	   windowName=StrCat (printerName," Properties")
	   SendKeysTo(windowName,"!t")
	   SendKeysTo(printerName,"~")
	   SendKeysTo(windowName,"~")
	   Display(5,"Information",StrCat ("Test Page has been sent to ",printerName))
	


WMI Win32_Printer classes

Win32_PrinterConfiguration

The Win32_Printer WMI class represents a device connected to a Windows computer system that can produce a printed image or text on paper or other medium. It can be used to control or get information about a local or remote printer.

The Win32_Printer class defines the following methods.

	Method			Description
	AddPrinterConnection	Adds connection to the printer. 
	CancelAll		Jobs Cancels all jobs. 
	Pause			Pauses the print queue. 
	PrintTestPage		Prints a test page. 
	RenamePrinter		Renames a printer. 
	Resume			Resumes paused print queue. 
	SetDefaultPrinter	Sets default printer. 
	
The Win32_Printer class defines the following properties.
	Attributes;
	Availability;
	AvailableJobSheets[];
	AveragePagesPerMinute;
	Capabilities[];
	CapabilityDescriptions[];
	Caption;
	CharSetsSupported[];
	Comment;
	ConfigManagerErrorCode;
	ConfigManagerUserConfig;
	CreationClassName;
	CurrentCapabilities[];
	CurrentCharSet;
	CurrentLanguage;
	CurrentMimeType;
	CurrentNaturalLanguage;
	CurrentPaperType;
	Default;
	DefaultCapabilities[];
	DefaultCopies;
	DefaultLanguage;
	DefaultMimeType;
	DefaultNumberUp;
	DefaultPaperType;
	DefaultPriority;
	Description;
	DetectedErrorState;
	DeviceID;
	Direct;
	DoCompleteFirst;
	DriverName;
	EnableBIDI;
	EnableDevQueryPrint;
	ErrorCleared;
	ErrorDescription;
	ErrorInformation[];
	ExtendedDetectedErrorState;
	ExtendedPrinterStatus;
	Hidden;
	HorizontalResolution;
	InstallDate;
	JobCountSinceLastReset;
	KeepPrintedJobs;
	LanguagesSupported[];
	LastErrorCode;
	Local;
	string Location;
	MarkingTechnology;
	MaxCopies;
	MaxNumberUp;
	MaxSizeSupported;
	MimeTypesSupported[];
	Name;
	NaturalLanguagesSupported[];
	Network;
	PaperSizesSupported[];
	PaperTypesAvailable[];
	Parameters;
	PNPDeviceID;
	PortName;
	PowerManagementCapabilities[];
	PowerManagementSupported;
	PrinterPaperNames[];
	PrinterState;
	PrinterStatus;
	PrintJobDataType;
	PrintProcessor;
	Priority;
	Published;
	Queued;
	RawOnly;
	SeparatorFile;
	ServerName;
	Shared;
	ShareName;
	SpoolEnabled;
	StartTime;
	Status;
	StatusInfo;
	SystemCreationClassName;
	SystemName;
	TimeOfLastReset;
	UntilTime;
	VerticalResolution;
	WorkOffline;
	
For example you can use WMI to handle printing a test page, as long as you’re running Windows XP. That’s because the revised Win32_Printer class introduced in Windows XP includes a method called PrintTestPage. As you might expect, this means you can bind to a given printer on a computer and then call the PrintTestPage method to print a test page. Here’s a sample script that does just that:
	strComputer = "."
	   objWMIService = GetObject(StrCat("winmgmts:\\" , strComputer , "\root\cimv2"))
	   colPrinters =  objWMIService.ExecQuery("Select * from Win32_Printer Where DeviceID = '\\\\Server\\HP LaserJet 5'")
	   ForEach objPrinter In colPrinters
	       objPrinter.PrintTestPage()
	   Next
	   colPrinters = 0
	   objWMIService = 0
	

Win32_PrinterConfiguration

The Win32_PrinterConfiguration WMI class defines the configuration for a printer device. This includes capabilities such as resolution, color, fonts, and orientation.

The Win32_PrinterConfiguration class defines the following properties.

	BitsPerPel;
	Caption;
	Collate;
	Color;
	Copies;
	Description;
	DeviceName;
	DisplayFlags;
	DisplayFrequency;
	DitherType;
	DriverVersion;
	Duplex;
	FormName;
	HorizontalResolution;
	ICMIntent;
	ICMMethod;
	LogPixels;
	MediaType;
	Name;
	Orientation;
	PaperLength;
	PaperSize;
	PaperWidth;
	PelsHeight;
	PelsWidth;
	PrintQuality;
	Scale;
	SettingID;
	SpecificationVersion;
	TTOption;
	VerticalResolution;
	XResolution;
	YResolution;
	
For example you can use WMI to get the color of the document. Some color printers have the capability to print using true black instead of a combination of cyan, magenta, and yellow (CMY). This usually creates darker and sharper text for documents. This option is only useful for color printers that support true black printing. This propery will return 1 for Monochrome or 2 for Color.

Here’s a sample script that does just that:

	strComputer = "."
	   objWMIService = GetObject(StrCat("winmgmts:\\" , strComputer , "\root\cimv2"))
	   colPrinters =  objWMIService.ExecQuery("Select * from Win32_PrinterConfiguration where Name = '\\\\Server\\HP LaserJet 5'")
	   ForEach objPrinter In colPrinters
	       color = objPrinter.color
	       Switch color
	          Case   1 ;Monochrome
	            Message("Color?","Monochrome")
	            Break
	         Case 2 ;Color
	            Message("Color?","Color")
	            Break
	       EndSwitch
	   Next
	   colPrinters = 0
	   objWMIService = 0
	   Exit
	
The DriverVersion property allows you to get the Version number of the Windows printer driver. The version numbers are created and maintained by the driver manufacturer.
	   strComputer = "."
	   objWMIService = GetObject(StrCat("winmgmts:\\" , strComputer , "\root\cimv2"))
	   colPrinters =  objWMIService.ExecQuery("Select * from Win32_PrinterConfiguration where Name = '\\\\Server\\HP LaserJet 5'")
	   ForEach objPrinter In colPrinters
	       DriverVersion = objPrinter.DriverVersion
	       Message("Driver Version",DriverVersion)
	   Next
	   colPrinters = 0
	   objWMIService = 0
	   Exit
	

Win32_PrinterDriver

The Win32_PrinterDriver WMI class represents the drivers for a Win32_Printer instance.

The Win32_PrinterDriver class defines the following properties.

	Caption;
	ConfigFile;
	CreationClassName;
	DataFile;
	DefaultDataType;
	DependentFiles[];
	Description;
	DriverPath;
	FilePath;
	HelpFile;
	InfName;
	InstallDate;
	MonitorName;
	Name;
	OEMUrl;
	Started;
	StartMode;
	Status;
	SupportedPlatform;
	SystemCreationClassName;
	SystemName;
	Version;
	
Here is some code that grabs a list of Printer drivers.
	strComputer = "."
	   objWMIService = GetObject(StrCat("winmgmts:\\" , strComputer , "\root\cimv2"))
	   colPrinters =  objWMIService.ExecQuery("Select * from Win32_PrinterDriver")
	   list = ""
	   ForEach objPrinter In colPrinters
	       list = StrCat(list, objPrinter.Name, @TAB)
	   Next
	   AskItemlist("Printer Driver List",StrTrim(list), @TAB, @UNSORTED, @SINGLE)
	   colPrinters = 0
	   objWMIService = 0
	   Exit
	

Win32_PrintJob

The Win32_PrintJob WMI class represents a print job that a Windows application generates. Any unit of work generated by the print command of an application that is running on a Windows system is a descendent or member of this class.

The Win32_PrintJob class defines the following methods.

	Method		Description
	Pause		Pauses a print job. 
	Resume		Continues a print job. 
	

The Win32_PrintJob class defines the following Properties.

	Caption;
	DataType;
	Description;
	Document;
	DriverName;
	ElapsedTime;
	HostPrintQueue;
	InstallDate;
	JobId;
	JobStatus;
	Name;
	Notify;
	Owner;
	PagesPrinted;
	Parameters;
	PrintProcessor;
	Priority;
	Size;
	StartTime;
	Status;
	StatusMask;
	TimeSubmitted;
	TotalPages;
	UntilTime;
	
Here is some code that gets the status of a print job (assuming there is one).
	strComputer = "."
	   objWMIService = GetObject(StrCat("winmgmts:\\" , strComputer , "\root\cimv2"))
	   colPrinters =  objWMIService.ExecQuery("Select * from Win32_PrintJob")
	   list = ""
	   ForEach objPrinter In colPrinters
	       list = StrCat(list, objPrinter.JobId, " | ", objPrinter.JobStatus, @TAB)
	   Next
	   AskItemlist("Printer Job Status",StrTrim(list), @TAB, @UNSORTED, @SINGLE)
	   colPrinters = 0
	   objWMIService = 0
	   Exit
	


PrnAdmin COM

PrnAdmin

The PrnAdmin utility lets you use scripts that perform administrative printer functions. You can create your own scripts or modify one of the sample scripts that is provided with PrnAdmin. Either way you can manage both local and remote printers using PrnAdmin. PrinterAdmin is available in the Microsoft Windows Resource Kit. It is a Component Object Model (COM)-based tool that administrators can use to manage printers, drivers, and ports on local and remote Windows computers.

PrinterAdmin provides large-scale, non-interactive control of printers through the use of scripts. You can either create your own scripts or modify one of the sample scripts that is provided with PrinterAdmin to perform the following tasks:

	Add or delete local or remote printers. 
	Add or delete printer connections. 
	Add or delete local or remote forms. 
	Add or delete ports on local or remote printers. 
	Add or delete printer drivers on local or remote printers. 
	View a list of ports, drivers, printers, or forms on local or remote printers. 
	Pause, resume, or purge a local or remote printer. 
	Configure a local or remote printer. 
	Print a test page. 
	Clone a print server.  
	
NOTE: This dll is generally included with the Windows Resource Kit. To use Prnadmin.dll, it must be registered on the client computer. The script registers Prnadmin.dll from its location on the server. Make sure that you change \\Servername\Foldername to the correct path to the Prnadmin.dll file on your server.

For more information about the Windows 2000 Resource Kit, visit the following Microsoft Web site: http://www.microsoft.com/windows2000/techinfo/reskit/default.asp#section1

Windows 2003 Resource kit can be downloaded here: http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en

Yuu must first register the PrnAdmin.dll file on the system before accessing any of it COM objects. To register prnadmin.dll you need to be an administrator or power user on the local machine. The "write/set" functionality in prnadmin requires print server or print queue administrative permissions.

Register PrnAdmin.dll

	; Register prnadmin.dll file on client computer
	   Run('regsvr32','"/s \\ServerName\FolderName\Prnadmin.dll",1,TRUE')
	

Create a port

	;***************************************************************************
	;**
	;**   Create the port first
	;**
	;***************************************************************************
	oPort = ObjectCreate("Port.Port.1")
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	oPort.PortName = "C:\MyFolder\MyPort"
	oPort.PortType = 3
	ErrorMode(@OFF)
	oMaster.PortAdd(oPort)
	ErrorMode(@CANCEL)
	If LastError()!=0
	   Message("Error","There was an error creating the port.")
	   Exit
	EndIf
	

Create a printer

	;***************************************************************************
	;**
	;**   Create the printer second
	;**
	;***************************************************************************
	; Change MyPrinter to the name of the printer that you are adding.
	; Change PrinterDriver to the name of the printer driver that you are adding.
	oPrinter = ObjectCreate("Printer.Printer.1")
	oPrinter.PrinterName = "MyPrinter"      ; name of the printer as it appears in the Printers folder
	oPrinter.DriverName = "PrinterDriver"      ; name that is referenced in ntprint.inf
	oPrinter.PortName = "C:\MyFolder\MyPort"      ; Specify a port name. Can also point to LPT or COM port.
	oMaster.PrinterAdd(oPrinter)
	ErrorMode(@CANCEL)
	If LastError()!=0
	   Message("Error","There was an error creating the printer.")
	   Exit
	EndIf
	Message("Done","The script is finished." )
	Exit
	

Delete a Printer

This sample code deletes a printer from a remote server.

	;The following code creates the required PrintMaster object.
	   oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	   ;The following code specifies the name of the printer on a remote computer to delete. To delete a local
	   ;printer, use empty quotes ("") in place of ServerName.
	   oMaster.PrinterDel( ServerName, PrinterName )
	
	   ;Clean up
	   oMaster = 0
	

Adding a Printer Connection

	The sample code adds a connection ON the local computer To a PRINTER already installed ON another computer.
	   ;The following code creates the required PrintMaster object.
	   oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	   ;The following code adds a connection on the local computer to a printer or a share name. The printer
	   ;connection is a per-user resource. The PrinterName value must use the following form: \\server\my printer.
	   oMaster.PrinterConnectionAdd( PrinterName )
	   oMaster = 0
	

Deleting a Printer Connection

This sample deletes a connection from the local computer to a printer installed on another computer.

	;The following code creates the required PrintMaster object.
	   oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	   ;The following code deletes a connection on the local computer to a printer. The ServerName property is 'not used because the printer connection is per user. The PrinterName must be the name of a printer and 'not a share. PrinterName must use the following form: \\server\myprinter.
	   oMaster.PrinterConnectionDel( PrinterName )
	   oMaster = 0
	

Getting the Configuration of a Printer

This sample gets the configuration settings of a local and remote printer.

	;The following code creates the required PrintMaster and Printer objects.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	oPrinter = ObjectCreate("Printer.Printer.1")
	
	;The following code gets the local printer's configuration settings.
	oMaster.PrinterGet("","My Printer", oPrinter)
	
	;The following code gets a remote printer's configuration settings without specifying the name of the remote
	;server where the printer is installed.
	oMaster.PrinterGet( "\\server", "My Printer", oPrinter)
	
	;The following code gets a remote printer's configuration settings and specifies the name of the remote
	;server where the printer is installed.
	oMaster.PrinterGet("", "\\server\My Printer", oPrinter)
	
	;The following code prints out the configuration if no errors occurred.
	data = ""
	title = StrCat("PrinterName: " , oPrinter.PrinterName)
	data = StrCat( data, @LF, "ShareName:    " & oPrinter.ShareName
	data = StrCat( data, @LF, "PortName:     " & oPrinter.PortName
	data = StrCat( data, @LF, "DriverName    " & oPrinter.DriverName
	data = StrCat( data, @LF, "Comment:      " & oPrinter.Comment
	data = StrCat( data, @LF, "Location:     " & oPrinter.Location
	data = StrCat( data, @LF, "SepFile:      " & oPrinter.Sepfile
	data = StrCat( data, @LF, "PrintProc:    " & oPrinter.PrintProcessor
	data = StrCat( data, @LF, "Datatype:     " & oPrinter.Datatype
	data = StrCat( data, @LF, "Parameters:   " & oPrinter.Parameters
	data = StrCat( data, @LF, "Attributes:   " & CStr(oPrinter.Attributes)
	data = StrCat( data, @LF, "Priority:     " & CStr(oPrinter.Priority)
	data = StrCat( data, @LF, "DefaultPri:   " & CStr(oPrinter.DefaultPriority)
	data = StrCat( data, @LF, "StartTime:    " & CStr(oPrinter.StartTime)
	data = StrCat( data, @LF, "UntilTime:    " & CStr(oPrinter.UntilTime)
	data = StrCat( data, @LF, "Status:       " & CStr(oPrinter.Status)
	data = StrCat( data, @LF, "Jobcount:     " & CStr(oPrinter.Jobs)
	data = StrCat( data, @LF, "AveragePPM    " & CStr(oPrinter.AveragePPM)
	Message( title, data)
	
	oMaster = 0
	oPrinter = 0
	

Configuring a Printer

This sample code gets the existing printer configuration, and then sets some properties. You can choose which settings you want to configure.

	;The following code creates the required PrintMaster and Printer objects.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	oPrinter = ObjectCreate("Printer.Printer.1")
	
	;The following code gets the existing printer settings. This step is optional; however, if you do not use it, you
	;will not know which options have been left on the default settings. Because there are so many properties
	;you can set, you might fail to enter a value, and the default settings might cause unwanted effects.
	oMaster.PrinterGet("\\server", "MyPrinter", oPrinter)
	
	;The following code sets the ServerName and is used only for a remote printer if you did not use 'PrinterGet.
	;If you did use PrinterGet, it fills in the ServerName property for you.
	oPrinter.ServerName = "\\server"
	
	;The following code sets some printer properties. Because there are so many settings, the following code
	;only configures a few settings. You might or might not want to set any of the following properties.
	oPrinter.PortName = "lpt1:"
	oPrinter.ShareName = "my share"
	oPrinter.Location = "my office"
	oPrinter.Comment = "my good printer"
	oPrinter.DataType = "RAW"
	oPrinter.NewName = "New Printer Name"
	oPrinter.SepFile = "c:\sep-file"
	;The following code sets printer attributes. They can be set to true or false to enable or disable the setting.
	oPrinter.Queued = @TRUE ;or @false
	oPrinter.Direct = @TRUE ;or @false
	oPrinter.Default = @TRUE ;or @false
	oPrinter.Shared = @TRUE ;or @false
	oPrinter.Hidden = @TRUE ;or @false
	oPrinter.EnableDevq = @TRUE ;or @false
	oPrinter.KeepPrintedJobs = @TRUE ;or @false
	oPrinter.DoCompleteFirst = @TRUE ;or @false
	oPrinter.WorkOffline = @TRUE ;or @false
	oPrinter.EnableBidi = @TRUE ;or @false
	oPrinter.RawOnly = @TRUE ;or @false
	oPrinter.Published = @TRUE ;or @false
	;The following code saves the printer settings.
	oMaster.PrinterSet( oPrinter)
	oMaster = 0
	oPrinter = 0
	

Pausing a Printer

This sample code pauses a local and remote printer.

	;The following code creates the required PrintMaster object.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code pauses a local printer.
	oMaster.PrinterPause( "", "MyLocalPrinter" )
	
	;The following code pauses a remote printer.
	oMaster.PrinterPause( "\\server", "MyPrinter" )
	
	;The following code can also be used to pause a remote printer.
	oMaster.PrinterPause( "", "\\server\MyPrinter")
	oMaster = 0
	

Resuming a Printer

This sample code resumes printer services for a local and remote printer.

	;The following code creates the required PrintMaster object.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code resumes a local printer.
	oMaster.PrinterResume( "", "MyLocalPrinter")
	
	;The following code resumes a remote printer.
	oMaster.PrinterResume( "\\server", "MyPrinter")
	
	;The following code can also be used to resume a remote printer.
	oMaster.PrinterResume( "", "\\server\MyPrinter")
	oMaster = 0
	

Purging a Printer

This sample code purges all print jobs from a local and remote printer.

	;The following code creates the required PrintMaster object.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code purges a local printer.
	oMaster.PrinterPurge( "", "MyLocalPrinter")
	
	;The following code purges a remote printer.
	oMaster.PrinterPurge( "\\server", "MyPrinter")
	
	;The following code can also be used to resume a remote printer.
	oMaster.PrinterPurge( "", "\\server\MyPrinter")
	oMaster = 0
	

Printing a Test Page

This sample code prints a test page on a local and remote printer.

	
	;The following code creates the required PrintMaster object.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code prints a test page on a local printer.
	oMaster.PrintTestPage( "", "MyLocalPrinter")
	
	;The following code prints a test page on a remote printer.
	oMaster.PrintTestPage( "\\server", "MyPrinter")
	
	;The following code can also be used to print a test page on a remote printer.
	oMaster.PrintTestPage( "", "\\server\MyPrinter")
	oMaster = 0
	

Enumerating Printers

This sample code lists all printers on a specific computer. Sample code is provided to include local printers in the list.

	;The following code creates the required PrintMaster object.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code specifies the name of a computer. The printer list will be created based on printers
	;installed on the specified computer. The only way to list printers connected to the local computer is to set
	;the value of the ServerName property to an empty string.
	list = ""
	ForEach oPrinter In oMaster.Printers("\\server")
	   list = StrCat( list, @TAB, "PrinterName      : " , oPrinter.PrinterName )
	Next
	list = StrTrim(list)
	AskItemlist("Printer List",list,@TAB,@UNSORTED,@SINGLE)
	oMaster = 0
	
Note: If you identify your printer by using another property instead of PrinterName, you can use any of the Printer object properties on the oPrinter object in the sample code above.

Adding a Printer Driver

	;The following code creates the required PrintMaster and Driver objects.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	oDriver = ObjectCreate("Driver.Driver.1")
	
	;The following code sets the driver name. It is required and the string cannot be empty.
	oDriver.ModelName = "drv x800"
	
	;The following code sets the driver processor. You must use either "Intel" or "Itanium."
	oDriver.DriverArchitecture = "Intel"
	
	;The following code specifies the operating system version for which the driver was written. If this setting is
	;not configured, the caller's environment is used. You can use one of the following sets of values:
	;"Windows 95, Windows 98, and Windows Millennium Edition"
	;"Windows NT 4.0 or 2000"
	;"Windows 2000, Windows XP and Windows Server 2003"
	;"Windows XP and Windows Server 2003"
	odriver.DriverVersion      = "Windows NT 4.0 or 2000"
	
	;The following code sets the driver cache. This setting is optional.
	oDriver.Path = "c:\files"
	
	;The following code sets the INF file. This setting is optional because if it is not set, the default directory,
	;%windir%\inf\ntprint.inf, is used.
	oDriver.InfFile            = "c:\ntprint.inf"
	
	;The following code sets a server name to add a driver remotely. If you do not specify a ServerName, or if
	;you use empty double quotes (""), the default, which adds a driver to the local computer, is used.
	oDriver.ServerName  = "\\server"
	
	;The following code adds the driver.
	oMaster.DriverAdd(oDriver)
	oMaster = 0
	oDriver = 0
	

Deleting a Printer Driver

	;The following code creates the required PrintMaster and Driver objects.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	oDriver = ObjectCreate("Driver.Driver.1")
	
	;The following code specifies the driver name. It is required and the string cannot be empty.
	oDriver.ModelName = "drv x800"
	
	;The following code sets the driver processor. You must use either "Intel", or "Itanium".
	oDriver.DriverArchitecture = "Intel"
	
	;The following code specifies the operating system version for which the driver was written. This setting is
	;required and the string cannot be empty. You must use one of the following sets of values:
	;"Windows 95 or 98"
	;"Windows NT 3.1"
	;"Windows NT 3.5 or 3.51"
	;"Windows NT 4.0"
	;"Windows NT 4.0 or 2000"
	;"Windows 2000"
	odriver.DriverVersion      = "Windows NT 4.0 or 2000"
	
	;The following code sets a server name to delete a driver remotely. If you do not specify a ServerName, or
	;if you use empty double quotes (""), the default, which deletes a driver from the local computer, is used.
	oDriver.ServerName  = "\\server"
	
	;The following code deletes the driver.
	oMaster.DriverDel(oDriver)
	oMaster = 0
	oDriver = 0
	

Enumerating Printer Drivers

Lists all printer drivers on a remote computer.

	;The following code creates the required PrintMaster and Driver objects.
	oMaster = ObjectCreate("PrintMaster.PrintMaster.1")
	
	;The following code specifies the name of a computer. The printer driver list will be created based on
	;printers installed on the specified computer. The only way to list printer drivers installed on the local
	;computer is to set the value of the ServerName property to an empty string.
	ForEach oDriver In oMaster.Drivers("\\server")
	   ;The following code gets the driver name.
	   Message("DriverName: " , oDriver.ModelName)
	
	   ;The following code gets the numerical driver version.
	   Message("Version: " , oDriver.Version)
	
	   ;The following code gets a string description of the driver, for example "Windows 2000".
	   Message("DriverVersion: " , oDriver.DriverVersion)
	
	   ;The following code gets the path where the files are.
	   Message("DriverPath: " , oDriver.Path)
	
	   ;The following code gets the environment of the driver, for example "Windows NT x86".
	   Message("Environment: " , oDriver.Environment)
	
	   ;The following code gets the architecture of the driver, for example "Intel".
	   Message("DriverEnv: " , oDriver.DriverArchitecture)
	
	   ;The following code gets the monitor name, if any.
	   Message("MonitorName: " , oDriver.MonitorName)
	Next
	oMaster = 0
	oDriver = 0
	
Adding Printer Ports
The sample code in this section demonstrates how to add a port by using the Port object. The Port object can add Standard TCP RAW, Standard TCP LPR, or Standard Local ports.
oPort = CreateObject("Port.Port.1")
oMaster = CreateObject("PrintMaster.PrintMaster.1")

;Indicate where to add the port. Double quotes ("" ) stand for the local computer, which is the default.
oPort.ServerName = "\\server"

;The name of the port cannot be omitted.
oPort.PortName = "IP_1.2.3.4"

;The type of the port can be 1 (TCP RAW), 2 (TCP LPR), or 3 (standard local).
oPort.PortType = 1

;Mandatory for TCP ports. This is the address of the device to which the port connects.
oPort.HostAddress = "1.2.3.4"

;For TCP RAW ports. Default is 9100.
oPort.PortNumber = 9102

;Enable or disable SNMP.
oPort.SNMP = @true / @false

;If SNMP is enabled, 1 is the default for index.
oPort.SNMPDeviceIndex = 2

;If SNMP is enabled, "public" is the default community name.
oPort.CommunityName = "public"

;Applies to TCP LPR name, default is LPR
oPort.QueueName = "Queue"

;Byte counting or double spool applies to TCP LPR ports, is disabled by default.
oPort.DoubleSpool = true / false

;Try adding the port.
oMaster.PortAdd oPort
Deleting Printer Ports
The sample code in this section demonstrates how to delete a port by using the Port object. The Port object can delete any type of port.
;Create the PrintMaster object.
oMaster = CreateObject("PrintMaster.PrintMaster.1")

;The first argument is the server name; can be "" for the local computer. The second argument is the name of a port.
oMaster.PortDel( "\\server", "c:\temp\localport.prn")
Enumerating Printer Ports
The sample code in this section demonstrates how to enumerate a port by using the Port object. Enumerating ports requires a PrintMaster object. The Port object is mandatory only if the explicit option is set.
;Create the PrintMaster object.
oMaster = CreateObject("PrintMaster.PrintMaster.1")

;The first argument in parenthesis is the server name. The parenthesis and the server name can be
;missing, in which case the local computer will provide the collection.
foreach oPort in oMaster.Ports("\\server")
   ;Name of the port.
   Pause( "PortName" , oPort.PortName)

   ;Monitor name if any.
   Pause(  "MonitorName" , oPort.MonitorName)

   ;Will return the port type string.
   Pause( "Description" , oPort.Description)
next
Note: If you list ports on a remote computer where you do not have administrative credentials, all ports other than local ports and TCP ports will have the PortType property set to the unknown port.

Getting the Configuration of a Printer Port
The sample code in this section demonstrates how to get the configuration of a port by using the Port object. The Port object can get the configuration of Standard TCP, HP DLC, and LPR MON port types.

;Create the Port object.
oPort = CreateObject("Port.Port.1")

;Create the PrintMaster object.
oPort = CreateObject("PrintMaster.PrintMaster.1")

;The first argument is the server name; can be "" for the local computer. The second argument is the name
;of the port. The third argument is a Port object, which will receive the settings of the specified port.
oMaster.PortGet ("\\server", "IP_1.2.3.4", oPort)

;The name of the port.
Pause("PortName" , oPort.PortName)

;The type of the port. "Description" is a function in Portmgr.vbs that converts a number that
;represents a port type to a string.
Pause( "PortType" , oPort.PortType)

;The address of the device to which it connects.
Pause("HostAddress" , oPort.HostAddress)

;The name of the queue (applies to LPR ports).
Pause( "QueueName" , oPort.QueueName)

;Applies to TCP RAW ports.
Pause( "PortNumber" , oPort.PortNumber )

;Check if SNMP is enabled.
if oPort.SNMP 
	; The SNMP device index.
	Pause( "SNMP Index" ,oPort.SNMPDeviceIndex)
	; The community name.
	Pause("Community" , oPort.CommunityName)
endif 

if oPort.DoubleSpool then
	;Byte counting is enabled.
else
	;Byte counting is disabled.
endif
Note:
Valid fields for each port type:
       SNMPDeviceIndex and CommunityName are present only if SNMP is enabled.
"	TCP RAW: PortName, PortType, HostAddress, PortNumber, SNMP
"	TCP LPR:  PortName, PortType, HostAddress, QueueName, DoubleSpool, SNMP 
"	HP DLC: PortName, PortType, HostAddress
"	LPR MON: PortName, PortType, HostAddress, QueueName
Setting the Configuration of a Printer Port
The sample code in this section demonstrates how to set the configuration of a Standard TCP port by using the Port object. It is recommended that you get the configuration of the port, then set any of the properties listed below, and then update the port.
;Create the Port object.
oPort = CreateObject("Port.Port.1")

;Create the PrintMaster object.
oMaster = CreateObject("PrintMaster.PrintMaster.1")

;Get the current configuration. The first argument is a server name; "" indicates local computer. The second
;one is a port name; the third argument is a Port object, which will receive the settings of the specified port.
oMaster.PortGet ("\\server", "IP_1.2.3.4", oPort)

;Set the new type: 1 (RAW) or 2 (LPR). 
oPort.PortType = 1

;Set the address of the device to which it connects.
oPort.HostAddress = "2.3.4.5"

;This applies to RAW ports only.
oPort.PortNumber = 9100

;This applies to LPR ports only.
oPort.QueueName = "Queue"

;Enable/disable SNMP.
oPort.SNMP = @true

;This applies if SNMP is enabled, SNMP device index.
oPort.SNMPDeviceIndex = 1

;This applies if SNMP is enabled, SNMP community name.
oPort.CommunityName = "public"

;Enable/disable byte counting (double spool).
oPort.DoubleSpool = @true ; @false

;Try updating the data.
oMaster.PortSet( oPort )
Converting Printer Ports
The sample code in this section demonstrates how to convert an existing LPR MON port into a TCP port. The only supported conversion is from LPR to TCP. The PortConversion method will query the device and Tcpmon.ini for the desired settings-such as protocol type (RAW or LPR), queue name, and port number-on that device. You can use the settings in the Port object passed as a parameter and add that corresponding port. If the device is not responding, the Port object will be configured with default settings. You will know if the device did not respond from the fact that oPort.DeviceType will be empty. The only situation in which this read-only property is not empty is if the device responded and the device type could be identified.
;Create the Port object.
oPort = CreateObject("Port.Port.1")

;Create the PrintMaster object.
oMaster = CreateObject("PrintMaster.PrintMaster.1")

;Set the IP address of the device.
oPort.HostAddress = "1.2.3.4"
 
;The only supported flag is kLprToTcp.

oMaster.PortConversion( oPort, kLprToTcp)

For more information about the PrinterAdmin tool, see the Prnadmin.doc file that is available in the Windows Resource Kit. The Prnadmin.doc file is located in the Program Files\Resource Kit folder (if the Windows Resource Kit is installed to the default location).


Print Graphic UDF

You can automate printing of Graphics files (i.e., BMP TIFF JPG JPEG GIF) using the following Internet Explorer OLE trick.

This code can print a graphic file, to the default printer, using Internet Explorers WebBrowser Objects.

NOTE: Internet Explorer 4.0 supports both OLECMDEXECOPT_PROMPTUSER and OLECMDEXECOPT_DONTPROMPTUSER. However, OLECMDID_DONTPROMPTUSER is ignored in Internet Explorer 5, because printing is considered to be a security issue. A Web page should not have the ability to start a print job without confirmation from the user. In Internet Explorer 5.5 and later, the print job is completed without user confirmation.

#DefineFunction PrintGraphic(File)
         ;This can be used to Print:
         ;HTML files
         ;Graphics files (i.e., BMP TIFF JPG JPEG GIF)
         ; Requires Windows 2000 or later.
         If WinVersion(1) < 5
             Message("Error","This function is not supported on this Windows platform")
             Return(0)
         EndIf
         objBrowser = ObjectCreate("InternetExplorer.Application")
         objBrowser.addressbar = @FALSE
         objBrowser.statusbar = @FALSE
         objBrowser.menubar = @FALSE
         objBrowser.toolbar = @FALSE
         objBrowser.visible = @FALSE
         objBrowser.navigate(file)
         While @TRUE
            If objBrowser.ReadyState == 4 Then Break
            TimeDelay(1)
         EndWhile
         objBrowserDoc = objBrowser.Document
         objAll = objBrowserdoc.all

         ;http://msdn.microsoft.com/library/en-us/com/htm/oen_a2z_22sk.asp?frame=true
         OLECMDID_PRINT = 6

         ;http://msdn.microsoft.com/library/en-us/com/htm/oen_a2z_5k38.asp?frame=true
         OLECMDEXECOPT_DONTPROMPTUSER  = 2

         ;http://msdn.microsoft.com/workshop/browser/mshtml/reference/constants/idm_print.asp
         PRINT_DONTBOTHERUSER = 1
         PRINT_WAITFORCOMPLETION = 2
         pvaIn = ObjectType("I2",PRINT_WAITFORCOMPLETION|PRINT_DONTBOTHERUSER)
         pvaOut = ObjectType("NULL","")

         ;http://msdn.microsoft.com/workshop/browser/webbrowser/reference/ifaces/iwebbrowser2/execwb.asp?frame=true
         objBrowser.ExecWB(OLECMDID_PRINT,OLECMDEXECOPT_DONTPROMPTUSER,pvaIn, pvaOut)

         ;Give the browser enough time to print before closing the object
         TimeDelay(1)

         objBrowserDoc = 0
         objAll = 0
         objBrowser = 0
         Return(1)
#EndFunction

file = "C:\Users\Fred\Pictures\Sample.jpg"
PrintGraphic(File)


Print Graphic Commandline

This code uses the Windows Printer and Fax Viewer ( shimgvw.dll,ImageView_PrintTo ) commandline to print a graphics file. It can be used to print all types of graphic files including: bmp, jgp, jpeg, gif, tif, tiff.

Requires:

    - Windows XP or later
    - shimgvw.dll is registered. 

Commandline:

rundll32.exe %SystemRoot%\System32\shimgvw.dll,ImageView_PrintTo /pt "<putyourfilenamehereinquotes>" "<putyourprinternamehereinquotes" "" ""
ImageView_PrintTo parameters explained:
 PrintTo switch. /pt
 param1:  Full file name in double quotes. "\\PicServer\Prints\dummy.tif" 
 param2:  Printer name in double quotes. '"\\computername\sharename"
 param3:  not used
 param4:  not used
; Print Graphic Files using shimgvw.dll,ImageView_PrintTo
;
; Commandline :
;    rundll32.exe %SystemRoot%\System32\shimgvw.dll,ImageView_PrintTo /pt "<putyourfilenamehereinquotes>" "<putyourprinternamehereinquotes" "" ""
;
; Requires:
;    - Windows XP or later
;    - shimgvw.dll is registered.
;
; ImageView_PrintTo parameters explained:
; PrintTo switch. /pt
; param1:  Full file name in double quotes. "\\PicServer\Prints\dummy.tif"
; param2:  Printer name in double quotes. '"\\computername\sharename"
; param3:  not used
; param4:  not used

If WinVersion(5) >= '2-5-1'
   AddExtender("WWPRT44i.DLL")
   printers = pGetPrtList(0)
   strPrinter = AskItemlist("Choose Printer", printers, @TAB, @SORTED, @SINGLE)
   ; Get Graphic File name i.e.
   strGraphic = AskFilename( 'Choose file to print', ShortCutDir( 'My Pictures' ), 'Pic Files|*.bmp;*.gif;*.jpg;*.jpeg;*.tif;*.tiff', '', 2 )
   RunHideWait('rundll32.exe', 'shimgvw.dll,ImageView_PrintTo /pt "':strGraphic:'" "':strPrinter:'"')
EndIf

Article ID:   W17356
File Created: 2010:02:17:11:58:07
Last Updated: 2014:07:18:13:31:06