Joris Groosman
Joris Groosman

Reputation: 781

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

Upvotes: 7

Views: 3551

Answers (3)

kobik
kobik

Reputation: 21232

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;

If you want to use this on a TWinControl variable you have to use the usual protected access trick:

type
  TWinControlAccess = class(TWinControl);

procedure Test(AWinControl: TWinControl);
var
  Canvas: TControlCanvas;
begin
  Canvas := TControlCanvas.Create;
  try
    Canvas.Control := AWinControl;
    Canvas.Font.Assign(TWinControlAccess(AWinControl).Font);

    // Do something with Canvas...
  finally
    Canvas.Free;
  end;
end;

Upvotes: 7

Garth Thornton
Garth Thornton

Reputation: 94

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.

Upvotes: 1

Joris Groosman
Joris Groosman

Reputation: 781

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;


Upvotes: 6

Related Questions