Numeric edit control with flat button inside and no calculator

雨燕双飞 提交于 2019-12-06 22:38:29

I'd use a TButtonedEdit to get the button, and to enforce floating-point input with a maximum of two decimals after the point, I'd do

TButtonedEdit = class(ExtCtrls.TButtonedEdit)
protected
  procedure KeyPress(var Key: Char); override;
  procedure WMPaste(var Message: TWMPaste); message WM_PASTE;
end;

...

procedure TButtonedEdit.KeyPress(var Key: Char);
  function InvalidInput: boolean;
  var
   dc: integer;
  begin
    result := false;
    if Character.IsControl(Key) then Exit;
    dc := Pos(DecimalSeparator, Text);
    if not (Key in ['0'..'9', DecimalSeparator]) then Exit(true);
    if Pos(DecimalSeparator, Text) > 0 then
    begin
      if Key = DecimalSeparator then Exit(true);
      if (Length(Text) - dc > 1)
        and (Pos(DecimalSeparator, Text) < SelStart + 1) and
        (SelLength = 0) then Exit(true);
    end;
  end;

begin
  inherited;
  if InvalidInput then
  begin
    Key := #0;
    beep;
  end;
end;

procedure TButtonedEdit.WMPaste(var Message: TWMPaste);
var
  s: string;
  i: integer;
  hasdc: boolean;
  NewText: string;
  NewSelStart: integer;
begin
  if Clipboard.HasFormat(CF_TEXT) then
  begin
    s := Clipboard.AsText;

    NewText := Text;
    Delete(NewText, SelStart + 1, SelLength);
    Insert(s, NewText, SelStart + 1);


    // Validate
    hasdc := false;
    for i := 1 to Length(NewText) do
    begin
      if NewText[i] = DecimalSeparator then
        if hasdc then
        begin
          beep;
          Exit;
        end
        else
          hasdc := true
      else if not (NewText[i] in ['0'..'9']) then
      begin
        beep;
        Exit;
      end;
    end;

    // Trim
    if hasdc then
      NewText := Copy(NewText, 1, Pos(DecimalSeparator, NewText) + 2);

    NewSelStart := SelStart + Length(s);
    Text := NewText;
    SelStart := NewSelStart;
    SelLength := 0;
  end
  else
    inherited;
end;

Sample demo EXE

Use stock VCL buttoned editor

http://docwiki.embarcadero.com/Libraries/en/Vcl.ExtCtrls.TButtonedEdit

Use OnChange to filter out wrong input (or use JvValidators)


Another approach, JediVCL-based one, would be to use base button-enabled editor
http://wiki.delphi-jedi.org/wiki/JVCL_Help:TJvComboEdit

This has EditMask property, just like TMaskEdit has, so you can tweak it to accept only digits.

And at very least OnChange event would allow u to filter non-numeric text input as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!