Delphi ,TEdit文本作为动作触发器

iyfamqjs  于 2023-04-20  发布在  其他
关注(0)|答案(3)|浏览(131)

我使用TEdit来允许用户输入一个数字,例如10。
我将TEdit.Text转换为整数,并调用计算过程。
在这个calc过程中,内置了一个检查,以确保不处理小于10的数字。
目前我使用的是OnChange事件。假设用户想要将'10'更改为例如'50'。但是一旦'10'被删除或'5'(后面跟着0)被键入,我就会触发警告,警告最小数字是10。也就是说,程序不会等到我完全键入5和0。
我尝试了OnEnterOnClickOnExit,但我似乎没有克服这个问题。唯一的解决方案是添加一个单独的按钮,将触发计算与新的数字。它的工作,但我可以没有按钮吗?

zdwk9cvp

zdwk9cvp1#

使用计时器进行延迟检查,例如:

procedure TForm1.Edit1Change(Sender: TObject);
begin
  // reset the timer
  Timer1.Enabled := false;
  Timer1.Enabled := true;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := false;
  // do your check here
end;

对于大多数用户来说,将计时器设置为500毫秒应该没问题。
正如大卫在对这个问题的评论中所建议的:不要显示错误对话框,而是使用一些不那么干扰的东西,例如在编辑或更改背景颜色附近的标签中显示错误消息。还有:不要不要阻止焦点从那个控件上移开,不要不要**播放声音,那也很烦人。
对于我们的内部软件,如果有错误,我们将控件的背景设置为黄色,并在状态栏中显示第一个错误的错误信息,同时也作为控件的提示。如果你这样做,你甚至可能不需要延迟。

cngwdvgl

cngwdvgl2#

谢谢,为您的帮助.我尝试了计时器选项,但无法得到它的工作.我现在有这个代码,它的作品(几乎-见下文),但需要使用总是键入CR:

procedure Calculate;
begin
  // this is my calculation procedure
  ShowMessage('calculation running correctly'); 
end;

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
N   : integer;
begin
  if Key = #13 then
  begin
    N := StrtoInt(Edit1.Text);
    if N<10 then ShowMessage('<10!') else
      if N>100 then ShowMessage('>100!') else Calculate;
  end;
end;

我在这里使用ShowMessage()只是为了看看示例代码是否有效。在真实的的程序中,我已经省略了这一点,正如你们所建议的那样。我还包括了“在错误输入时变黄”(谢谢大卫)。唯一的问题是,如果用户运行这个,我会从我的计算机中听到哔哔声。我看不出出什么问题。但是是什么导致了哔哔声?

e5nqia27

e5nqia273#

Embarcadero提供了一种替代解决方案:
https://blogs.embarcadero.com/validating-input-in-tedit-components/
它解决了如下问题。首先创建一个用户定义的消息,如下所示:

const
        { User-defined message }
        um_ValidateInput = wm_User + 100;

在表单中,定义一个验证过程和一个重新聚焦对象:

private
      Refocusing: TObject;
      { User-defined message handler }
      procedure ValidateInput(var M: TMessage); message um_ValidateInput;
  end;

然后执行validate-、editenter-和editexit过程:

procedure TForm5.ValidateInput(var M: TMessage);
     var
     E : TEdit;
       begin
         { The following line is my validation.  I want to make sure }
         { the first character is a lower case alpha character.  Note }
         { the typecast of lParam to a TEdit. }
         E := TEdit(M.lParam);
         if not (E.Text[1] in ['a'..'z']) then begin
         Refocusing := E;                       { Avoid a loop     }
         ShowMessage('Bad input');              { Yell at the user }
         TEdit(E).SetFocus;                     { Set focus back   }
       end;
     end;

    procedure TForm5.EditExit(Sender: TObject);
      begin
        { Post a message to myself which indicates it's time to  }
        { validate the input.  Pass the TEdit instance (Self) as }
        { the message lParam. }
        if Refocusing = nil then
        PostMessage(Handle, um_ValidateInput, 0, longint(Sender));
      end;

    procedure TForm5.EditEnter(Sender: TObject);
      begin
        if Refocusing = Sender then
        Refocusing := nil;
      end;

这种方法对我很有效……

相关问题