Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in textbox when it gets focus

In Windows phone, how can I select all text in Textbox when the TextBox has focus?

I try setting the get focus property of Textbox:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox .SelectAll();
    }

What I see is I see all the text is being selected for 1-2 sec and then it goes back to cursor mode (i.e. 1 blink line).

like image 917
hap497 Avatar asked Nov 05 '14 01:11

hap497


People also ask

What is TextBox focus () in C?

Textbox. Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus() . Follow this answer to receive notifications.

What is TextBox focus?

Description: The Focused event fires when the TextBox gains focus - typically when a client clicks/taps on a TextBox to begin text entry. This also fires if a TextBox forces focus on the user. It can be used alongside TextBox.

How do I select a TextBox?

To select the text box, you need to click the border of the text box, and the insertion point disappears. If you press Tab or Ctrl+Tab while the insertion point is visible in the text box, then you only modify the text in the text box; you don't select the next object.


2 Answers

I had this same problem on WPF and managed to solve it. Not sure if you can use what I used but essentially your code would look like:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox .CaptureMouse()
    }

    private void TextBox_GotMouseCapture(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

private void TextBox_IsMouseCaptureWithinChanged(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

All events hooked up to the original textbox. If this doesn't work for you, maybe you can replace CaptureMouse with CaptureTouch (and use the appropriate events). Good luck!

like image 92
Tyress Avatar answered Oct 23 '22 11:10

Tyress


You can try this code,

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        String sSelectedText = mytextbox.SelectedText;
    }

If user clicks on copy icon that comes after selection it will get copied, if you want to do it programmatically you can try this

DataPackage d = new DataPackage();
d.SetText(selectedText);
Clipboard.SetContent(d);

I would suggest doing the copying in some other event rather than gotfocus, as this will be triggered immediately after user taps on text field so this method will be called when there is no text actually entered.

like image 1
Prasanna Aarthi Avatar answered Oct 23 '22 11:10

Prasanna Aarthi