delphicanvasdlltcanvas

Delphi TCanvas object become corrupted after using from dll, how to restore?


Have some problem. I have a form with a canvas, I need access to this canvas from dll by its handle. I do this in this way:

from dll

canvas := TCanvas.Create;
  try
    canvas.Handle := handle;
    // do some painting on this canvas
  finally
    canvas.free;
  end;

It works well, I paint what I need from dll. But this trick has side effect. After painting from dll, form loses font settings (btw I did not use fonts when painted from dll, just few rects) and when I paint on same canvas from main form, even if I do directly canvas.font.size := ...; canvas.font.name := ...; before canvas.TextOut, the font does not change. Lines, filling and other paintings are ok. But fonts become corrupted (sometimes not, but mostly).

Is there a way to reset/reinit TCanvas object of the form?


Solution

  • Canvas does not have any reset functionality but you can ask the api to save the state of the device context of the canvas, and restore it after your drawing.

    var
      SavedDC: Integer;
    
      ...
      SavedDC := SaveDC(handle);
      try
        canvas := TCanvas.Create;
        try
          canvas.Handle := handle;
          // do some painting on this canvas
        finally
          canvas.free;
        end;
      finally
        RestoreDC(handle, SavedDC);
      end;
    


    Remy's answer explains how you lose the sate of the device context. Why it doesn't always happen should depend on timing I believe. If the form has entered a new paint cycle at the time its canvas uses its font, all should be well since it operates on a newly acquired and setup device context.