Практическое руководство. Клонирование принтера

В какой-то момент большинство предприятий приобретает несколько принтеров одной модели. Как правило, все они устанавливаются с практически идентичными параметрами конфигурации. Установка каждого принтера требует времени и подвержена ошибкам. Пространство имен System.Printing.IndexedProperties и класс InstallPrintQueue, предоставляемые в Microsoft .NET Framework, позволяют мгновенно установить любое количество дополнительных очередей печати, клонированных из существующей очереди печати.

Пример

В приведенном ниже примере вторая очередь печати клонируется из существующей очереди печати. Вторая отличается от первой только именем, расположением, портом и общем состоянием. Порядок действий таков.

  1. Создайте объект PrintQueue для существующего принтера, который будет клонирован.

  2. Создайте PrintPropertyDictionary из PropertiesCollectionPrintQueue. Свойство Value каждой записи в этом словаре является объектом одного из типов, производных от PrintProperty. Существует два способа задать значение записи в этом словаре.

    • Используйте методы словаря Remove и Add, чтобы удалить запись, а затем повторно добавить ее с нужным значением.

    • Используйте метод словаря SetProperty.

    В приведенном ниже примере показаны оба способа.

  3. Создайте объект PrintBooleanProperty и присвойте его Name значение IsShared, а Value — значение true.

  4. Используйте объект PrintBooleanProperty в качестве значения записи IsShared PrintPropertyDictionary.

  5. Создайте объект PrintStringProperty и присвойте его Name значение ShareName, а его Value — соответствующее значение String.

  6. Используйте объект PrintStringProperty в качестве значения записи ShareName PrintPropertyDictionary.

  7. Создайте еще один объект PrintStringProperty и присвойте его Name значение Location, а его Value — соответствующее значение String.

  8. Используйте второй объект PrintStringProperty в качестве значения записи Location PrintPropertyDictionary.

  9. Создайте массив объектов String. Каждый элемент — это имя порта на сервере.

  10. Используйте InstallPrintQueue для установки нового принтера с новыми значениями.

Пример представлен ниже.

LocalPrintServer myLocalPrintServer = new LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer);
PrintQueue sourcePrintQueue = myLocalPrintServer.DefaultPrintQueue;
PrintPropertyDictionary myPrintProperties = sourcePrintQueue.PropertiesCollection;

// Share the new printer using Remove/Add methods
PrintBooleanProperty shared = new PrintBooleanProperty("IsShared", true);
myPrintProperties.Remove("IsShared");
myPrintProperties.Add("IsShared", shared);

// Give the new printer its share name using SetProperty method
PrintStringProperty theShareName = new PrintStringProperty("ShareName", "\"Son of " + sourcePrintQueue.Name +"\"");
myPrintProperties.SetProperty("ShareName", theShareName);

// Specify the physical location of the new printer using Remove/Add methods
PrintStringProperty theLocation = new PrintStringProperty("Location", "the supply room");
myPrintProperties.Remove("Location");
myPrintProperties.Add("Location", theLocation);

// Specify the port for the new printer
String[] port = new String[] { "COM1:" };

// Install the new printer on the local print server
PrintQueue clonedPrinter = myLocalPrintServer.InstallPrintQueue("My clone of " + sourcePrintQueue.Name, "Xerox WCP 35 PS", port, "WinPrint", myPrintProperties);
myLocalPrintServer.Commit();

// Report outcome
Console.WriteLine("{0} in {1} has been installed and shared as {2}", clonedPrinter.Name, clonedPrinter.Location, clonedPrinter.ShareName);
Console.WriteLine("Press Return to continue ...");
Console.ReadLine();
Dim myLocalPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Dim sourcePrintQueue As PrintQueue = myLocalPrintServer.DefaultPrintQueue
Dim myPrintProperties As PrintPropertyDictionary = sourcePrintQueue.PropertiesCollection

' Share the new printer using Remove/Add methods
Dim [shared] As New PrintBooleanProperty("IsShared", True)
myPrintProperties.Remove("IsShared")
myPrintProperties.Add("IsShared", [shared])

' Give the new printer its share name using SetProperty method
Dim theShareName As New PrintStringProperty("ShareName", """Son of " & sourcePrintQueue.Name & """")
myPrintProperties.SetProperty("ShareName", theShareName)

' Specify the physical location of the new printer using Remove/Add methods
Dim theLocation As New PrintStringProperty("Location", "the supply room")
myPrintProperties.Remove("Location")
myPrintProperties.Add("Location", theLocation)

' Specify the port for the new printer
Dim port() As String = { "COM1:" }


' Install the new printer on the local print server
Dim clonedPrinter As PrintQueue = myLocalPrintServer.InstallPrintQueue("My clone of " & sourcePrintQueue.Name, "Xerox WCP 35 PS", port, "WinPrint", myPrintProperties)
myLocalPrintServer.Commit()

' Report outcome
Console.WriteLine("{0} in {1} has been installed and shared as {2}", clonedPrinter.Name, clonedPrinter.Location, clonedPrinter.ShareName)
Console.WriteLine("Press Return to continue ...")
Console.ReadLine()

См. также