Appendix B Getting the Installed Printers

As discussed in Chapter 10, the ActivePrinter property can set the active printer. This raises the issue of how to determine the installed printers on a given computer. Unfortunately, VBA does not seem to provide a way to do this. (Visual Basic has a Printers collection, but Visual Basic for Applications does not.)

In this appendix, we describe a program for getting this printer information. As mentioned in Chapter 10, this program uses the Windows API. To use this program, just type it into your own code, as described here.

The first step is to declare some special constants in the Declarations section of a standard module:

Public Const KEY_ENUMERATE_SUB_KEYS = &H8 Public Const HKEY_LOCAL_MACHINE = &H80000002 Public Const SUCCESS = 0&

Next, we need to declare a user-defined type. We have not discussed these data structures in this book, but a user-defined type is essentially just a custom data type. Enter the following code into the Declarations section:

Type FILETIME

dwLowDateTime As Long dwHighDateTime As Long End Type

Then we need to declare three API functions. As you can see, these are relatively complicated functions as VBA functions go, but not as API functions go. Enter the following in the Declarations section:

Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias

"RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As _ String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias

"RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As _ Long, ByVal lpName As String, lpcbName As Long, ByVal lpReserved As Long, ByVal lpClass As String, lpcbClass As Long, lpftLastWriteTime As FILETIME) As Long Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

We are now ready for the main procedure, shown in Example B-1, which will extract the names of the installed printers from the Windows registry.

0 0

Post a comment