TEdit onclick select all?

2019-05-12 22:13发布

问题:

How to select all text of a TEdit1 whenever user click on it or click to select some text of it

回答1:

How to select all text of a TEdit1 whenever user click on it

Select Edit1 in the VCL editor and double-click on the OnClick event:

procedure TForm13.Edit1Click(Sender: TObject);
begin
  Edit1.SelectAll;
end;

You can also link this event to another control like a button.
Select the button, choose and click on the V arrow to select an event you want to link.

Now both Edit1.OnClick and Button1.OnClick link to the same event.



回答2:

It can be quite dangerous to do anything beyond the default behaviour of the TEdit control. Your users know how the standard Windows controls behave and any deviation from this is likely to cause confusion.

By default the AutoSelect property is set to True.

Determines whether all the text in the edit control is automatically selected when the control gets focus.

Set AutoSelect to select all the text when the edit control gets focus. AutoSelect only applies to single-line edit controls.

Use AutoSelect when the user is more likely to replace the text in the edit control than to append to it.

When this property is True, the entire contents of the edit control are selected when it gets the focus by means of keyboard action. If the control gets the focus by a mouse click then the contents will not all be selected. In that case you simply press CTRL+A to select all. A double click will select the word underneath the mouse. This is all standard behaviour implemented by the underlying Windows control.


If you change the select in response to the OnClick event, as per the currently selected answer, then you will find that it is impossible to move the caret with a mouse click. This is exceedingly counter-intuitive behaviour.

This is a classic example of why you need to be very careful about changing the behaviour of a control from its default. It's simply very easy not to miss a particular use case when testing but when your users get hold of the program, they are sure to find all such wrinkles.

What you could safely do is to call SelectAll from OnDblClick. This would, I believe have no annoying side-effects.

Another option would be to call SelectAll when the focus switched to the edit control, but not every time you click in the control. This might feel a little odd to the user, but I personally think it would be reasonable to take this course of action. If you want to do this you need to handle the OnEnter event of your edit control:

procedure TForm1.Edit1Enter(Sender: TObject);
begin
  PostMessage(Edit1.Handle, EM_SETSEL, 0, -1);
end;


回答3:

How to select some text of a TEdit1 whenever user click on it:

procedure TForm1.Edit1Click(Sender: TObject);
begin
  Edit1.SelStart:= 1;
  Edit1.SelLength:= 2;
end;