In the Mainpage
constructor, I have this line :
PrintManager.GetForCurrentView().PrintTaskRequested += OnPrintTaskRequested;
I have a button in menubar for printing with this click event handler:
CanvasPrintDocument printDocument;
public async void PrintButtonClick()
{
if (printDocument != null)
{
printDocument.Dispose();
}
printDocument = new CanvasPrintDocument();
printDocument.Preview += (sender, args) =>
{
sender.SetPageCount(1);
PrintPage(args.DrawingSession, args.PrintTaskOptions.GetPageDescription(1));
};
printDocument.Print += (sender, args) =>
{
using var ds = args.CreateDrawingSession();
PrintPage(ds, args.PrintTaskOptions.GetPageDescription(1));
};
try
{
await PrintManager.ShowPrintUIAsync();
}
catch (Exception)
{
}
}
private void PrintPage(CanvasDrawingSession ds, PrintPageDescription printPageDescription)
{
//
}
This button also has Keyboard accelerator CTRL + P.
Now, this works for me in my machine, in debug and release mode, no problem.
However, I am getting some crash reports of my app that says the error:
A method was called at an unexpected time.
Only one handler for the PrintTaskRequested event may be registered at a time.
I don't get it how the PrintTaskRequested
event is registered more than once at a time. Since the event handler registration code is in the constructor.
I don't have any other printing logic in my app.
Any help is appreciated. Thanks.
if the event registration occurs in the constructor of MainPage, you can check whether the application may navigate to MainPage multiple times.
But a more common approach is to cancel the event before registering it.
PrintManager.GetForCurrentView().PrintTaskRequested -= OnPrintTaskRequested;
PrintManager.GetForCurrentView().PrintTaskRequested += OnPrintTaskRequested;
This ensures that only one print event is always registered.
Thanks.