locked
Printing in a C# Windows Store App RRS feed

  • Question

  • Hello. I am working on a Windows Store App, and it must be able to print. As of right now, the App starts, loads the MainPage, and then makes a new instance of a class. The class runs fine until it gets to the method

    PrintManager printMan = PrintManager.GetForCurrentView();

    Where it says:

    Invalid window handle.

    Windows.Graphics.Printing.PrintManager is not supported on the view provided.

    Any ideas on what I am doing wrong. Thank You.


    Sincerely, Jakeinc

    Sunday, November 3, 2013 11:44 PM

Answers

  • I'm pretty sure that the problem is that you're doing this in the constructor rather than in the OnNavigatedTo method.  I don't think that there's even a view at the time that the constructor is called.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Tuesday, November 5, 2013 2:26 PM
    Moderator

All replies

  • Without seeing the project, I feel like this code is running on a background thread.  Can you try putting this in a dispatcher to see if it corrects the problem?

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, November 4, 2013 1:59 PM
    Moderator
  • Hi Jakeinc,

    No, no idea.  Please:

    1.  Look at the Printing samples in the sample section

    2.  Post a simplified repro of your project on SkyDrive so people can look further into the issue.

    Jeff


    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

    Monday, November 4, 2013 2:16 PM
    Moderator
  • using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.System;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Core;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.UI.Xaml.Printing;
    using Windows.UI.Popups;
    using Windows.ApplicationModel.Activation;
    using Windows.ApplicationModel.DataTransfer;
    using Windows.ApplicationModel.DataTransfer.ShareTarget;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.Storage.Streams;
    using Windows.Storage;
    using Windows.Graphics.Printing;
    using Windows.ApplicationModel.Core;
    namespace PrintScreenshot
    {
        public partial class Page
        {
            protected const double ApplicationContentMarginLeft = 0.075;
            protected const double ApplicationContentMarginTop = 0.03;
            protected PrintDocument printDocument = null;
            internal List<UIElement> printPreviewPages = null;
            public IPrintDocumentSource PrintDocumentSource;
            protected FrameworkElement firstPage;
            protected virtual Canvas PrintingRoot
            {
                get
                {
                    return FindName("printingRoot") as Canvas;
                }
            }
            protected event EventHandler pagesCreated;
            public Page()
            {
                this.InitializeComponent();
                imagebox1.Source = MainPage.bitmapImage;
                RegisterForPrinting();
            }
            protected virtual void RegisterForPrinting()
            {
                printPreviewPages = new List<UIElement>();
                printDocument = new PrintDocument();
                PrintDocumentSource = printDocument.DocumentSource;
                printDocument.Paginate += CreatePrintPreviewPages;
                printDocument.GetPreviewPage += GetPrintPreviewPage;
                printDocument.AddPages += AddPrintPages;
                PrintManager printMan = PrintManager.GetForCurrentView();
                printMan.PrintTaskRequested += PrintTaskRequested;
                PreparePrintContent();
            }
            public void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
            {
                printPreviewPages.Clear();
                PrintingRoot.Children.Clear();
                PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
                PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
                AddOnePrintPreviewPage(pageDescription);
                if (pagesCreated != null)
                {
                    pagesCreated.Invoke(printPreviewPages, null);
                }
    
                PrintDocument printDoc = (PrintDocument)sender;
    
                // Report the number of preview pages created
                printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate);
            }
            public void AddOnePrintPreviewPage(PrintPageDescription printPageDescription)
            {
                // XAML element that is used to represent to "printing page"
                FrameworkElement page;
                // If this is the first page add the specific scenario content
                page = firstPage;
                //Hide footer since we don't know yet if it will be displayed (this might not be the last page) - wait for layout
                StackPanel footer = (StackPanel)page.FindName("footer");
                footer.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                // Set "paper" width
                page.Width = printPageDescription.PageSize.Width;
                page.Height = printPageDescription.PageSize.Height;
                Grid printableArea = (Grid)page.FindName("printableArea");
                // Get the margins size
                // If the ImageableRect is smaller than the app provided margins use the ImageableRect
                double marginWidth = Math.Max(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2);
                double marginHeight = Math.Max(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2);
                // Set-up "printable area" on the "paper"
                printableArea.Width = firstPage.Width - marginWidth;
                printableArea.Height = firstPage.Height - marginHeight;
                // Add the (newley created) page to the printing root which is part of the visual tree and force it to go
                // through layout so that the linked containers correctly distribute the content inside them.            
                PrintingRoot.Children.Add(page);
                PrintingRoot.InvalidateMeasure();
                PrintingRoot.UpdateLayout();
                // Add the page to the page preview collection
                printPreviewPages.Add(page);
            }
            public void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
            {
                PrintDocument printDoc = (PrintDocument)sender;
                printDoc.SetPreviewPage(e.PageNumber, printPreviewPages[e.PageNumber - 1]);
            }
            public void AddPrintPages(object sender, AddPagesEventArgs e)
            {
                // Loop over all of the preview pages and add each one to  add each page to be printied
                for (int i = 0; i < printPreviewPages.Count; i++)
                {
                    // We should have all pages ready at this point...
                    printDocument.AddPage(printPreviewPages[i]);
                }
    
                PrintDocument printDoc = (PrintDocument)sender;
    
                // Indicate that all of the print pages have been provided
                printDoc.AddPagesComplete();
            }
            public void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
            {
                PrintTask printTask = null;
                printTask = e.Request.CreatePrintTask("Print Screenshot", sourceRequestedArgs =>
                {
                    IList<string> displayedOptions = printTask.Options.DisplayedOptions;
                    printTask.Options.MediaSize = PrintMediaSize.NorthAmericaLegal;
                    printTask.Completed += async (s, args) =>
                    {
                        // Notify the user when the print operation fails.
                        if (args.Completion == PrintTaskCompletion.Failed)
                        {
                            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                            {
                                MainPage.DisplayError();
                            });
                        }
                    };
                    sourceRequestedArgs.SetSource(PrintDocumentSource);
                });
            }
            public void PreparePrintContent()
            {
    
            }
        }
    }
    

    Here is the page created with

    new Page();If you need more information, then please just ask.


    Sincerely, Jakeinc

    Monday, November 4, 2013 8:55 PM
  • I'm pretty sure that the problem is that you're doing this in the constructor rather than in the OnNavigatedTo method.  I don't think that there's even a view at the time that the constructor is called.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Tuesday, November 5, 2013 2:26 PM
    Moderator
  • Spot on Matt!

    Jeff Sanders (MSFT)

    @jsandersrocks - Windows Store Developer Solutions @WSDevSol
    Getting Started With Windows Azure Mobile Services development? Click here
    Getting Started With Windows Phone or Store app development? Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

    Tuesday, November 5, 2013 3:21 PM
    Moderator