Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 265
Joris Groosman Avatar asked Dec 06 '15 15:12

Joris Groosman


Video Answer


3 Answers

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;
like image 134
kobik Avatar answered Oct 22 '22 02:10

kobik


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;


like image 35
Joris Groosman Avatar answered Oct 22 '22 00:10

Joris Groosman


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.

like image 1
Garth Thornton Avatar answered Oct 22 '22 02:10

Garth Thornton