Delphi 进入TEdit控件时选中该控件中的内容,不使用SelectAll

来源:互联网 发布:奥迪tt知乎 编辑:程序博客网 时间:2024/04/28 12:08

T(Custom)Edit's AutoSelect property determines whether all the text in the edit control is automatically selected when the control gets focus.

The AutoSelect property has the value of TRUE by default - when the control receives the focus, i.e. when the control is tabbed into all the text in the control will be selected.

And here's a problem! The AutoSelect will auto select the text in an edit control only when the control receives the focus as a result of TAB key.

AutoSelect On Click Focus

What I need is that all the text is selected even when the edit control receives the focus from a mouse click.

There's the OnEnter event which gets fired when the control receives the focus. There's a SelectAll method which selects all text in the edit control. When you click into a non-focused edit control, it will receive the focus and the OnEnter event will get fired.

If you put "Edit.SelectAll" in the OnEnter event, presuming that the text will be selected when the control receives the focus - you are wrong :(

The default behavior for the OnClick event sets the caret to the clicked position, clearing any selection if there was one.

The OnClick is called after the OnEnter, this is why calling SelectAll in OnEnter will not work - the "hidden" OnClick behavior will clear the selection.

Also, you cannot simply place the call to SelectAll in the OnClick event handler as every time the user clicks into the edit control that already has the input focus - all the text will be selected.

SelectAll On First OnClick Focus

What we want is that AutoSelect works not only when the control is tabbed into BUT also when the edit control receives the input focus as a result of a mouse click into the control.

.

And finally, here's a simple trick to make this happen:

//Edit1 OnClick
procedure TEntryForm.Edit1Click(Sender: TObject);
begin
  Edit1.SelectAll;

  Edit1.OnClick := nil;
end;

//Edit1 OnExit (lost focus)
procedure TEntryForm.Edit1Exit(Sender: TObject);
begin
  Edit1.OnClick := Edit1Click;
end;

When the OnClick event is fired, the event handler select all the text, then detaches the event handling procedure (Edit1Click) from the event handler.

This ensures the auto selection will not happen as a result of mouse clicks inside the edit WHILE the edit has the input focus.

To restore the OnClick event handler, set it back again in the OnExit event - when the input focus shifts away from the edit control to another.

Of course, you basically loose the OnClick functionality while the edit has the focus ... but you can live without that ;)

原创粉丝点击