I want to shorten a filename to fit in a TEdit, something like
Edit1.Text := MinimizeName(FileName, Edit1.Canvas, Edit1.Width);
Unfortunately this doesn't compile because a TEdit does have a Canvas property directly. The canvas is needed for its font metrics.
How can I access a TEdit's canvas?
(MinimizeName is declared in Vcl.FileCtrl.) 
You could use TControlCanvas. You should also take the control's Font into account.
e.g.:
var
  Canvas: TControlCanvas;
Canvas := TControlCanvas.Create;
try
  Canvas.Control := Edit1;
  Canvas.Font.Assign(Edit1.Font); 
  // Do something with Canvas... 
finally
  Canvas.Free;
end;
                        OK, I found it. For those who are interested:
procedure TForm1.Button1Click(Sender: TObject);  
var  
  aCanvas: TCanvas;  
begin  
  if FileOpenDialog1.Execute then begin  
    aCanvas := TCanvas.Create;  
    try  
      aCanvas.Handle := GetDC(Edit1.Handle);  
      Edit1.Text := MinimizeName(FileOpenDialog1.FileName, aCanvas, Edit1.Width - 8);  
    finally  
      ReleaseDC(Edit1.Handle, aCanvas.Handle);
      aCanvas.Free;  
    end;  
  end;  
end;
Since the canvas is only used to get the metric, if you assume that the TEdit metric is the same as the form metric, it is sufficient to use the form canvas in the MinimizeName call. This is simpler, and valid unless there is a reason why the metric would differ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With