yoy.be "Why-o-Why"

Printer.Canvas is not threadsafe!

2012-01-26 19:46  i3003  delphi  [permalink]

What a strange discovery I made today. I was hunting down a weird exception we noticed in the logs of the live system.

It turns out that a 'global' callback procedure is being called when you use Printer.Canvas (Printer.Canvas.StretchDraw in my case) by the GDI subsystem. The default AbortProc in Printers.pas calls Application.ProcessMessages, which was causing trouble in my case.

There's a quick workaround:

function MyAbortProc(Prn: HDC; Error: Integer): Bool; stdcall;
begin
  Result := not FPrinter.Aborted;
end;

And then right after Printer.BeginDoc; call SetAbortProc(Printer.Canvas.Handle,MyAbortProc);

twitter reddit linkedin facebook