Example B The Get InstalledPrinters Procedure

Public Sub GetInstalledPrinters(ByRef sPrinters() As String, ByRef cPrinters As Long)

' Sets cPrinters to the number of installed printers. ' Sizes and fills sPrinters array with the names ' of these printers.


Dim KeyHandle As Long Dim KeyName As String Dim KeyLen As Long Dim Response As Long

On Error GoTo ERR_INSTALLED_PRINTERS ReDim sPrinters(1 To 5)

cPrinters = 0

' Open registry key whose subkeys are installed printers Response = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

"SYSTEM\CurrentControlSet\Control\Print\Printers", 0, KEY_ENUMERATE_SUB_KEYS, KeyHandle)

' If Error display message and exit If Response <> SUCCESS Then

MsgBox "Could not open the registry key." Exit Sub End If

' Loop to get subkeys Do

KeyLen = 1000 ' Plenty of room for printer name KeyName = String(KeyLen, 0) ' Fill with 0s

Response = RegEnumKeyEx(KeyHandle, cPrinters, KeyName, KeyLen, 0&, vbNullString, 0&, ft)

' If unsuccessful, then exit If Response <> SUCCESS Then Exit Do

' Next free index cPrinters = cPrinters + 1

' Make room if necessary If UBound(sPrinters) < cPrinters Then

ReDim Preserve sPrinters(1 To cPrinters + 5) End If

' Add to array sPrinters(cPrinters) = Left(KeyName, KeyLen) Loop

RegCloseKey KeyHandle Exit Sub

ERR_INSTALLED_PRINTERS: MsgBox Err.Description Exit Sub End Sub

The GetInstalledPrinters procedure has two parameters: a String array named sPrinters and a Long named cPrinters. The procedure will set the value of cPrinters to the number of installed printers and resize and fill the sPrinters array with the names of the printers.

Example B-2 shows how to use the GetInstalledPrinters subroutine. It simply gathers the printer names in a single String variable and displays that variable.

0 0

Post a comment