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

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 ;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值