How can I get a TEdit's canvas in Delphi?

3.3k views Asked by At

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.)

3

There are 3 answers

1
kobik On BEST ANSWER

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;
9
Joris Groosman On

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;


0
Garth Thornton On

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.