Djordje Djelic
Djordje Djelic

Reputation: 23

Edit and onEnter event

I have problem with several things:

  1. How to make edit1.text be blank when i hit enter (i think it should be on onEnter event but not so sure)
  2. Is there any way to assign strings from Edit1.text to array?

With all that said all i wanna do is:

Enter a name in edit, click enter, and then enter another name in same edit and previous name to be saved in some variable or array. Is this even possible?

I tried procedure TForm1.Edit3Enter(Sender: TObject); but when i click enter nothing happens.

Upvotes: 0

Views: 5767

Answers (2)

CiucaS
CiucaS

Reputation: 2128

Let's build a simple project. Add an TEdit and an TListbox to a form.

 unit Unit1;

    interface

    uses
      Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
      Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

    type
      TForm1 = class(TForm)
        Edit1: TEdit;
        ListBox1: TListBox;
        procedure Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
        procedure Edit1Enter(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;

    var
      Form1: TForm1;

    implementation

    {$R *.dfm}
    procedure TForm1.Edit1Enter(Sender: TObject);
    begin
     ShowMessage('On enter');
    end;

    procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    begin
      if Key = 13 then
      begin
        ListBox1.Items.Add(Edit1.Text);
        Edit1.Text := '';
      end;

    end;

    end.

To detect key pressed event use any of the Key Down/Key Up events, I used Key Down. Everytime I hit enter the string for the edit goes into the ListBox.

This is on delphi XE7.

Also for your information. onEnter event it's triggered when you set the focus on the edit field. For example on the same project assign the onEnter event. Now click on the listBox then click on the Edit1 you will trigger the onEnter event.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 597205

The OnEnter event is triggered when the Edit control receives keyboard input, not when the user pressed the Enter key. You should be using the OnKeyPress event for that, eg:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
  S: String;
begin
  if Key = #13 then
  begin
    Key := #0;  
    S := Edit1.Text;
    Edit1.Clear;
    // do something with S...
  end;
end;

Upvotes: 10

Related Questions