Select the whole text on focus

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Select the whole text on focus

Aliket
Hi Vadim,

I have a dialog with some text fields on it, and i want the text to be selected when the ctrl gain focus. So i implemented this little game (select on focus) like this:

void OnSetFocus(wxFocusEvent& event)
{
    wxWindow* focus = wxWindow::FindFocus();

    if (focus)
    {
        wxTextCtrl* txtCtrl = wxDynamicCast(focus, wxTextCtrl);

        if (txtCtrl)
        {
            CallAfter([=]()
            {
                if (txtCtrl->HasFocus())
                {
                    wxSafeYield( txtCtrl, true );
                    txtCtrl->SetInsertionPointEnd();
                    txtCtrl->SelectAll();
                }
            });
        }
    }

    event.Skip();
}

Is this the right way to go ?

Note that if i remove wxSafeYield() call, the text got selected till the cursor where i actually clicked inside the ctrl which may result in the text got partially selected !!

--
Please read http://www.wxwidgets.org/support/mlhowto.htm before posting.

To unsubscribe, send email to [hidden email]
or visit http://groups.google.com/group/wx-users
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Select the whole text on focus

Vadim Zeitlin-4
On Tue, 11 Apr 2017 17:49:47 -0700 (PDT) Aliket wrote:

A> I have a dialog with some text fields on it, and i want the text to be
A> selected when the ctrl gain focus. So i implemented this little game
A> (select on focus) like this:
A>
A> void OnSetFocus(wxFocusEvent& event)
A> {
A>     wxWindow* focus = wxWindow::FindFocus();
A>
A>     if (focus)
A>     {
A>         wxTextCtrl* txtCtrl = wxDynamicCast(focus, wxTextCtrl);
A>
A>         if (txtCtrl)
A>         {
A>             CallAfter([=]()
A>             {
A>                 if (txtCtrl->HasFocus())
A>                 {
A>                     wxSafeYield( txtCtrl, true );
A>                     txtCtrl->SetInsertionPointEnd();
A>                     txtCtrl->SelectAll();
A>                 }
A>             });
A>         }
A>     }
A>
A>     event.Skip();
A> }
A>
A> Is this the right way to go ?

 I don't see why do you need CallAfter() and you definitely shouldn't need
wxSafeYield(). You should be able to just call SelectAll() directly from
wxEVT_SET_FOCUS handler. Also, you should use wxFocusEvent::GetWindow()
instead of FindFocus(). And, finally, SetInsertionPointEnd() is just
unnecessary.

 Regards,
VZ

--
TT-Solutions: wxWidgets consultancy and technical support
               http://www.tt-solutions.com/

attachment0 (203 bytes) Download Attachment
Loading...