Поделиться через


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

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

Пример

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

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

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

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

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

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

  3. Создайте объект PrintBooleanProperty и задайте для Name значение IsShared и его Value значение true.

  4. Используйте объект PrintBooleanProperty, чтобы быть значением записи PrintPropertyDictionaryIsShared.

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

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

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

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

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

  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()

См. также