Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want to access a list of the printers available to the current Windows user.

Solution

The "printing" section of GDI+, the .NET drawing system, includes a list of the installed printers. Use the following code to display the names of each:

For Each printerName As String In _ System.Drawing.Printing.PrinterSettings.InstalledPrinters MsgBox(printerName) Next printerName

Discussion

An early beta version of Visual Basic 2005 did include a My. Printers collection, but it was removed before the final release. But that's okay, because .NET supplies printer information through other .NET classes. The System.Drawing. Printing.PrinterSettings.InstalledPrinters collection (of strings) lists the printers attached to the local workstation.

If you need to get a list of all printers available on the local network and not just installed on the local workstation, you can access the information through the Windows Management Instrumentation (WMI) features installed with .NET. By default, the WMI library is not included in new .NET projects, so you must add a reference to the library yourself. In the Project Properties window, select the References tab, and use the Add button to add a reference to System.Management.dll to the project. Now use the following code to list all network printers:

Dim printerQuery As Management.ManagementObjectSearcher Dim queryResults As Management.ManagementObjectCollection Dim onePrinter As Management.ManagementObject printerQuery = New Management.ManagementObjectSearcher( _ "SELECT * FROM Win32_Printer") queryResults = printerQuery.Get() For Each onePrinter In queryResults MsgBox(onePrinter!Name) Next onePrinter

Категории