Procedura: convalidare e unire PrintTicket

Lo schema di stampa di Microsoft Windows include gli elementi flessibili ed PrintTicket estendibiliPrintCapabilities. Il primo crea un elemento delle funzionalità di un dispositivo di stampa e quest'ultimo specifica in che modo il dispositivo deve usare tali funzionalità rispetto a una determinata sequenza di documenti, singoli documenti o singole pagine.

Una sequenza tipica di attività per un'applicazione che supporta la stampa sarà la seguente.

  1. Determinare le funzionalità di una stampante.

  2. Configurare un PrintTicket oggetto per l'uso di tali funzionalità.

  3. Convalidare l'oggetto PrintTicket.

Questo articolo illustra come eseguire questa operazione.

Esempio

Nell'esempio semplice riportato di seguito, ci interessa solo se una stampante può supportare la stampa fronte retro, ovvero la stampa a due lati. I passaggi principali sono i seguenti.

  1. Ottenere un PrintCapabilities oggetto con il GetPrintCapabilities metodo .

  2. Verificare la presenza della funzionalità desiderata. Nell'esempio seguente viene testata la DuplexingCapability proprietà dell'oggetto PrintCapabilities per verificare la presenza della funzionalità di stampa su entrambi i lati di un foglio di carta con la rotazione della pagina lungo il lato lungo del foglio. Poiché DuplexingCapability è una raccolta, viene usato il Contains metodo di ReadOnlyCollection<T>.

    Nota

    Questo passaggio non è strettamente necessario. Il MergeAndValidatePrintTicket metodo usato di seguito verificherà ogni richiesta nell'oggetto PrintTicket rispetto alle funzionalità della stampante. Se la funzionalità richiesta non è supportata dalla stampante, il driver della stampante sostituirà una richiesta alternativa nell'oggetto PrintTicket restituito dal metodo .

  3. Se la stampante supporta il duplex, il codice di esempio crea un oggetto PrintTicket che richiede il duplex. Tuttavia, l'applicazione non specifica tutte le possibili impostazioni della stampante disponibili nell'elemento PrintTicket . Questo sarebbe sprecato sia per il programmatore che per il tempo del programma. Al contrario, il codice imposta solo la richiesta di duplex e quindi lo unisce PrintTicket a un oggetto esistente, completamente configurato e convalidato, , PrintTicketin questo caso, l'impostazione predefinita PrintTicketdell'utente.

  4. Di conseguenza, l'esempio chiama il MergeAndValidatePrintTicket metodo per unire il nuovo, minimo, PrintTicket con l'impostazione predefinita PrintTicketdell'utente. Restituisce un oggetto ValidationResult che include il nuovo PrintTicket oggetto come una delle relative proprietà.

  5. L'esempio verifica quindi che la nuova PrintTicket richiesta sia in modalità duplex. In tal caso, l'esempio lo rende il nuovo ticket di stampa predefinito per l'utente. Se il passaggio 2 precedente fosse stato lasciato fuori e la stampante non supportava il duplex lungo il lato lungo, il test avrebbe generato false. Vedere la nota precedente.

  6. L'ultimo passaggio significativo consiste nel eseguire il commit della modifica alla UserPrintTicket proprietà di PrintQueue con il Commit metodo .

/// <summary>
/// Changes the user-default PrintTicket setting of the specified print queue.
/// </summary>
/// <param name="queue">the printer whose user-default PrintTicket setting needs to be changed</param>
static private void ChangePrintTicketSetting(PrintQueue queue)
{
    //
    // Obtain the printer's PrintCapabilities so we can determine whether or not
    // duplexing printing is supported by the printer.
    //
    PrintCapabilities printcap = queue.GetPrintCapabilities();

    //
    // The printer's duplexing capability is returned as a read-only collection of duplexing options
    // that can be supported by the printer. If the collection returned contains the duplexing
    // option we want to set, it means the duplexing option we want to set is supported by the printer,
    // so we can make the user-default PrintTicket setting change.
    //
    if (printcap.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge))
    {
        //
        // To change the user-default PrintTicket, we can first create a delta PrintTicket with
        // the new duplexing setting.
        //
        PrintTicket deltaTicket = new PrintTicket();
        deltaTicket.Duplexing = Duplexing.TwoSidedLongEdge;

        //
        // Then merge the delta PrintTicket onto the printer's current user-default PrintTicket,
        // and validate the merged PrintTicket to get the new PrintTicket we want to set as the
        // printer's new user-default PrintTicket.
        //
        ValidationResult result = queue.MergeAndValidatePrintTicket(queue.UserPrintTicket, deltaTicket);

        //
        // The duplexing option we want to set could be constrained by other PrintTicket settings
        // or device settings. We can check the validated merged PrintTicket to see whether the
        // the validation process has kept the duplexing option we want to set unchanged.
        //
        if (result.ValidatedPrintTicket.Duplexing == Duplexing.TwoSidedLongEdge)
        {
            //
            // Set the printer's user-default PrintTicket and commit the set operation.
            //
            queue.UserPrintTicket = result.ValidatedPrintTicket;
            queue.Commit();
            Console.WriteLine("PrintTicket new duplexing setting is set on '{0}'.", queue.FullName);
        }
        else
        {
            //
            // The duplexing option we want to set has been changed by the validation process
            // when it was resolving setting constraints.
            //
            Console.WriteLine("PrintTicket new duplexing setting is constrained on '{0}'.", queue.FullName);
        }
    }
    else
    {
        //
        // If the printer doesn't support the duplexing option we want to set, skip it.
        //
        Console.WriteLine("PrintTicket new duplexing setting is not supported on '{0}'.", queue.FullName);
    }
}
''' <summary>
''' Changes the user-default PrintTicket setting of the specified print queue.
''' </summary>
''' <param name="queue">the printer whose user-default PrintTicket setting needs to be changed</param>
Private Shared Sub ChangePrintTicketSetting(ByVal queue As PrintQueue)
    '
    ' Obtain the printer's PrintCapabilities so we can determine whether or not
    ' duplexing printing is supported by the printer.
    '
    Dim printcap As PrintCapabilities = queue.GetPrintCapabilities()

    '
    ' The printer's duplexing capability is returned as a read-only collection of duplexing options
    ' that can be supported by the printer. If the collection returned contains the duplexing
    ' option we want to set, it means the duplexing option we want to set is supported by the printer,
    ' so we can make the user-default PrintTicket setting change.
    '
    If printcap.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge) Then
        '
        ' To change the user-default PrintTicket, we can first create a delta PrintTicket with
        ' the new duplexing setting.
        '
        Dim deltaTicket As New PrintTicket()
        deltaTicket.Duplexing = Duplexing.TwoSidedLongEdge

        '
        ' Then merge the delta PrintTicket onto the printer's current user-default PrintTicket,
        ' and validate the merged PrintTicket to get the new PrintTicket we want to set as the
        ' printer's new user-default PrintTicket.
        '
        Dim result As ValidationResult = queue.MergeAndValidatePrintTicket(queue.UserPrintTicket, deltaTicket)

        '
        ' The duplexing option we want to set could be constrained by other PrintTicket settings
        ' or device settings. We can check the validated merged PrintTicket to see whether the
        ' the validation process has kept the duplexing option we want to set unchanged.
        '
        If result.ValidatedPrintTicket.Duplexing = Duplexing.TwoSidedLongEdge Then
            '
            ' Set the printer's user-default PrintTicket and commit the set operation.
            '
            queue.UserPrintTicket = result.ValidatedPrintTicket
            queue.Commit()
            Console.WriteLine("PrintTicket new duplexing setting is set on '{0}'.", queue.FullName)
        Else
            '
            ' The duplexing option we want to set has been changed by the validation process
            ' when it was resolving setting constraints.
            '
            Console.WriteLine("PrintTicket new duplexing setting is constrained on '{0}'.", queue.FullName)
        End If
    Else
        '
        ' If the printer doesn't support the duplexing option we want to set, skip it.
        '
        Console.WriteLine("PrintTicket new duplexing setting is not supported on '{0}'.", queue.FullName)
    End If
End Sub

In modo da poter testare rapidamente questo esempio, il resto di esso viene presentato di seguito. Creare un progetto e uno spazio dei nomi e quindi incollare entrambi i frammenti di codice in questo articolo nel blocco dello spazio dei nomi.

/// <summary>
/// Displays the correct command line syntax to run this sample program.
/// </summary>
static private void DisplayUsage()
{
    Console.WriteLine();
    Console.WriteLine("Usage #1: printticket.exe -l \"<printer_name>\"");
    Console.WriteLine("      Run program on the specified local printer");
    Console.WriteLine();
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in printer_name.");
    Console.WriteLine();
    Console.WriteLine("Usage #2: printticket.exe -r \"\\\\<server_name>\\<printer_name>\"");
    Console.WriteLine("      Run program on the specified network printer");
    Console.WriteLine();
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in server_name or printer_name.");
    Console.WriteLine();
    Console.WriteLine("Usage #3: printticket.exe -a");
    Console.WriteLine("      Run program on all installed printers");
    Console.WriteLine();
}

[STAThread]
static public void Main(string[] args)
{
    try
    {
        if ((args.Length == 1) && (args[0] == "-a"))
        {
            //
            // Change PrintTicket setting for all local and network printer connections.
            //
            LocalPrintServer server = new LocalPrintServer();

            EnumeratedPrintQueueTypes[] queue_types = {EnumeratedPrintQueueTypes.Local,
                                                       EnumeratedPrintQueueTypes.Connections};

            //
            // Enumerate through all the printers.
            //
            foreach (PrintQueue queue in server.GetPrintQueues(queue_types))
            {
                //
                // Change the PrintTicket setting queue by queue.
                //
                ChangePrintTicketSetting(queue);
            }
        }//end if -a

        else if ((args.Length == 2) && (args[0] == "-l"))
        {
            //
            // Change PrintTicket setting only for the specified local printer.
            //
            LocalPrintServer server = new LocalPrintServer();
            PrintQueue queue = new PrintQueue(server, args[1]);
            ChangePrintTicketSetting(queue);
        }//end if -l

        else if ((args.Length == 2) && (args[0] == "-r"))
        {
            //
            // Change PrintTicket setting only for the specified remote printer.
            //
            String serverName = args[1].Remove(args[1].LastIndexOf(@"\"));
            String printerName = args[1].Remove(0, args[1].LastIndexOf(@"\")+1);
            PrintServer ps = new PrintServer(serverName);
            PrintQueue queue = new PrintQueue(ps, printerName);
            ChangePrintTicketSetting(queue);
         }//end if -r

        else
        {
            //
            // Unrecognized command line.
            // Show user the correct command line syntax to run this sample program.
            //
            DisplayUsage();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        Console.WriteLine(e.StackTrace);

        //
        // Show inner exception information if it's provided.
        //
        if (e.InnerException != null)
        {
            Console.WriteLine("--- Inner Exception ---");
            Console.WriteLine(e.InnerException.Message);
            Console.WriteLine(e.InnerException.StackTrace);
        }
    }
    finally
    {
        Console.WriteLine("Press Return to continue...");
        Console.ReadLine();
    }
}//end Main
''' <summary>
''' Displays the correct command line syntax to run this sample program.
''' </summary>
Private Shared Sub DisplayUsage()
    Console.WriteLine()
    Console.WriteLine("Usage #1: printticket.exe -l ""<printer_name>""")
    Console.WriteLine("      Run program on the specified local printer")
    Console.WriteLine()
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in printer_name.")
    Console.WriteLine()
    Console.WriteLine("Usage #2: printticket.exe -r ""\\<server_name>\<printer_name>""")
    Console.WriteLine("      Run program on the specified network printer")
    Console.WriteLine()
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in server_name or printer_name.")
    Console.WriteLine()
    Console.WriteLine("Usage #3: printticket.exe -a")
    Console.WriteLine("      Run program on all installed printers")
    Console.WriteLine()
End Sub


<STAThread>
Public Shared Sub Main(ByVal args() As String)
    Try
        If (args.Length = 1) AndAlso (args(0) = "-a") Then
            '
            ' Change PrintTicket setting for all local and network printer connections.
            '
            Dim server As New LocalPrintServer()

            Dim queue_types() As EnumeratedPrintQueueTypes = {EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections}

            '
            ' Enumerate through all the printers.
            '
            For Each queue As PrintQueue In server.GetPrintQueues(queue_types)
                '
                ' Change the PrintTicket setting queue by queue.
                '
                ChangePrintTicketSetting(queue)
            Next queue 'end if -a

        ElseIf (args.Length = 2) AndAlso (args(0) = "-l") Then
            '
            ' Change PrintTicket setting only for the specified local printer.
            '
            Dim server As New LocalPrintServer()
            Dim queue As New PrintQueue(server, args(1))
            ChangePrintTicketSetting(queue) 'end if -l

        ElseIf (args.Length = 2) AndAlso (args(0) = "-r") Then
            '
            ' Change PrintTicket setting only for the specified remote printer.
            '
            Dim serverName As String = args(1).Remove(args(1).LastIndexOf("\"))
            Dim printerName As String = args(1).Remove(0, args(1).LastIndexOf("\")+1)
            Dim ps As New PrintServer(serverName)
            Dim queue As New PrintQueue(ps, printerName)
            ChangePrintTicketSetting(queue) 'end if -r

        Else
            '
            ' Unrecognized command line.
            ' Show user the correct command line syntax to run this sample program.
            '
            DisplayUsage()
        End If
    Catch e As Exception
        Console.WriteLine(e.Message)
        Console.WriteLine(e.StackTrace)

        '
        ' Show inner exception information if it's provided.
        '
        If e.InnerException IsNot Nothing Then
            Console.WriteLine("--- Inner Exception ---")
            Console.WriteLine(e.InnerException.Message)
            Console.WriteLine(e.InnerException.StackTrace)
        End If
    Finally
        Console.WriteLine("Press Return to continue...")
        Console.ReadLine()
    End Try
End Sub

Vedi anche