Cancel UWP Print Task

Jeremy Nelson 1 Reputation point
2020-02-08T03:57:20.52+00:00

I'm implementing a print feature in a UWP app, and I cannot find any nice way to cancel the print task after clicking Print on the preview page. Our users may be printing dozens or even hundreds of pages at a time, which takes awhile to send to the printer, so having a cancel option is very important.

The user's workflow is:

  1. Select some pages to print
  2. Configure some custom print options
  3. Show the Print UI with the preview (PrintManager.ShowPrintUIAsync())
  4. Click print
  5. Show a progress bar/status while the job is being sent to the printer. This can take awhile, so a cancel option needs to be available here.

I'm following the print sample: https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/Printing I cannot find any way to cancel in PrintManager, PrintTask, PrintTaskRequest, AddPagesEventArgs, PrintTaskProgressingEventArgs, etc.

My only idea is to use a CancellationTokenSource and throw if cancellation is requested, but this seems like a hacky workaround. Am I missing something?

Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. Jeremy Nelson 1 Reputation point
    2020-02-10T18:14:12.713+00:00

    I can sort of cancel if I use a CancellationTokenSource and check for cancellation in the AddPages event handler.

    protected async void AddPrintPages(object sender, AddPagesEventArgs args)
            {
                PrintDocument printDoc = (PrintDocument)sender;
                for ( uint i = 0; i < _pageCount; i++)
                {
                    if (_cancellationToken.IsCancellationRequested) 
                        break;
    
                     var page = await GetPrintPageAsync(i)
                     printDoc.AddPage(page);
                }           
    
                printDoc.AddPagesComplete();
            }
    

    This skips the remainder of the pages, but any pages that have already been added to the print doc will still be sent.

    0 comments No comments