Is it possible to determine if the text in a dbEdit is longer than what is visible?

我只是一个虾纸丫 提交于 2019-12-03 13:39:25

I think this should work...

function CanShowAllText(Edit: TDBEdit):Boolean;
var
    TextWidth:Integer;
    VisibleWidth: Integer;
    Bitmap: TBitmap;
const
//This could be worked out but without delphi I can't remember all that goes into it.
    BordersAndMarginsWidthEtc = 4;
begin
    Bitmap := TBitmap.Create;
    try
        Bitmap.Canvas.Font.Assign(Edit.Font);
        TextWidth := Bitmap.Canvas.TextWidth(Edit.Text);
        VisibleWidth := Edit.Width - BordersAndMarginsWidthEtc;
        Result := TextWidth < VisibleWidth;
    finally
        Bitmap.Free;
    end;
end;

Here is a fast version (without a TBitmap overhead) that takes into account the Edit control's Margins (i.e. EM_SETMARGINS).

Use IsEditTextOverflow below to determine if the Text overflows the visible area.

type
  TCustomEditAccess = class(TCustomEdit);

function EditTextWidth(Edit: TCustomEdit): Integer;
var
  DC: HDC;
  Size: TSize;
  SaveFont: HFont;
begin
  DC := GetDC(0);
  SaveFont := SelectObject(DC, TCustomEditAccess(Edit).Font.Handle);
  GetTextExtentPoint32(DC, PChar(Edit.Text), Length(Edit.Text), Size);
  SelectObject(DC, SaveFont);
  ReleaseDC(0, DC);
  Result := Size.cx;
end;

function EditVisibleWidth(Edit: TCustomEdit): Integer;
var
  R: TRect;
begin
  SendMessage(Edit.Handle, EM_GETRECT, 0, LPARAM(@R));
  Result := R.Right - R.Left;
end;

function IsEditTextOverflow(Edit: TCustomEdit): Boolean;
begin
  Result := EditTextWidth(Edit) > EditVisibleWidth(Edit);
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!