163

When a C# WinForms textbox receives focus, I want it to behave like your browser's address bar.

To see what I mean, click in your web browser's address bar. You'll notice the following behavior:

  1. Clicking in the textbox should select all the text if the textbox wasn't previously focused.
  2. Mouse down and drag in the textbox should select only the text I've highlighted with the mouse.
  3. If the textbox is already focused, clicking does not select all text.
  4. Focusing the textbox programmatically or via keyboard tabbing should select all text.

I want to do exactly this in WinForms.

FASTEST GUN ALERT: please read the following before answering! Thanks guys. :-)

Calling .SelectAll() during the .Enter or .GotFocus events won't work because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text.

Calling .SelectAll() during the .Click event won't work because the user won't be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user's text selection.

Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work because it breaks rule #2 above, it will keep overriding the user's selection on focus.

Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212

31 Answers31

111

First of all, thanks for answers! 9 total answers. Thank you.

Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts.

Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.)

bool alreadyFocused;

...

textBox1.GotFocus += textBox1_GotFocus;
textBox1.MouseUp += textBox1_MouseUp;
textBox1.Leave += textBox1_Leave;

...

void textBox1_Leave(object sender, EventArgs e)
{
    alreadyFocused = false;
}


void textBox1_GotFocus(object sender, EventArgs e)
{
    // Select all text only if the mouse isn't down.
    // This makes tabbing to the textbox give focus.
    if (MouseButtons == MouseButtons.None)
    {
        this.textBox1.SelectAll();
        alreadyFocused = true;
    }
}

void textBox1_MouseUp(object sender, MouseEventArgs e)
{
    // Web browsers like Google Chrome select the text on mouse up.
    // They only do it if the textbox isn't already focused,
    // and if the user hasn't selected all text.
    if (!alreadyFocused && this.textBox1.SelectionLength == 0)
    {
        alreadyFocused = true;
        this.textBox1.SelectAll();
    }
}

As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar.

Hopefully this helps the next guy who tries to solve this deceptively simple problem.

Thanks again, guys, for all your answers that helped lead me towards the correct path.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212
  • What about when focus is programmatically set to a TextBox? I have that problem as discussed here: http://stackoverflow.com/questions/24790704/how-could-a-textboxs-cursor-move-to-the-beginning-of-the-text-after-calling-sel I was able to solve it, after a fashion, but I am still nervous about it, as my "fix" seems rather kludgy. – B. Clay Shannon-B. Crow Raven Jul 17 '14 at 18:34
  • You wrote, "Calling .SelectAll() during the .Enter or .GotFocus events won't work because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text." I do have SelectAll in the GotFocus event which, for the most part, works. In fact, I would think the cursor being placed where the user clicked is "a good thing." I just want it to always be selected when focus is set to the TextBox programmatically. – B. Clay Shannon-B. Crow Raven Jul 17 '14 at 18:52
  • And I'm here again! :) – dotNET Dec 26 '14 at 03:10
  • 3
    You should move the `alreadyFocused = true;` in MouseUp out of the if-statement. Because if you immediately select parts of the text, the next click will select the whole text again. – Robert S. Mar 18 '16 at 08:51
  • There is a one liner answer below ---BeginInvoke((Action)MyTextBox.SelectAll); --- Worth looking at. It seems to do everything required – General Grey Aug 04 '16 at 12:23
  • That one liner doesn't work in all circumstances. To see why, look at the comments provided to each answer. – Judah Gabriel Himango Aug 04 '16 at 15:52
84

I found a simpler solution to this. It involves kicking off the SelectAll asynchronously using Control.BeginInvoke so that it occurs after the Enter and Click events have occurred:

In C#:

private void MyTextBox_Enter(object sender, EventArgs e)
{
    // Kick off SelectAll asynchronously so that it occurs after Click
    BeginInvoke((Action)delegate
    {
        MyTextBox.SelectAll();
    });
}

In VB.NET (thanks to Krishanu Dey)

Private Sub MyTextBox_Enter(sender As Object, e As EventArgs) Handles MyTextBox.Enter 
    BeginInvoke(DirectCast(Sub() MyTextBox.SelectAll(), Action)) 
End Sub
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Duncan Smart
  • 31,172
  • 10
  • 68
  • 70
  • 5
    Smartest Answer I've ever found.. Thanks a lot.. For VB.net Here is the Solution.. `Private Sub MyTextBox_Enter(sender As Object, e As EventArgs) Handles MyTextBox.Enter BeginInvoke(DirectCast(Sub() MyTextBox.SelectAll(), Action)) End Sub` – Krishanu Dey Oct 29 '13 at 09:47
  • Class Much 'Best solution, such web browser URL bar, much class End Class – ar.dll Feb 18 '14 at 15:58
  • 7
    In .Net 4.0 you can do: BeginInvoke((Action)MyTextBox.SelectAll); – JoelFan May 08 '14 at 17:44
  • Brilliant. Any way you can make this asynchronous should work. My preferred method: private void textBoxDirectory_Enter(object sender, EventArgs e) { SynchronizationContext.Current.Post((state) => { textBoxDirectory.SelectAll(); }, null); } – Chad Schouggins May 28 '14 at 18:43
  • Very good! I had to also add the call in GotFocus though as the textbox I had was part of a custom combobox and never got the Enter event when the drop down closed and the textbox regained focus. – kjbartel Jun 12 '14 at 00:08
  • @DuncanSmart: I have to agree with K. Dey (you lived up to the pressure of living up to your name). However, presumably because of the archaic and somewhat debilitated version of .NET I'm working with (Compact Framework, and so old that I have to use XPMode and VS 2003 to work with the project), I have no OnEnter event with my textbox. The only likely candidates is GotFocus. Would the same methodology (BeginInvoke, etc.) apply there? – B. Clay Shannon-B. Crow Raven Jul 17 '14 at 19:03
  • 2
    Unfortunately, BeginInvoke does not work for me (doubtless due to my disastrously dusty version of Dot net). Prepending "Control." to it does not help, nor does prepending the name of the TextBox itself. Alone, and palely loitering... – B. Clay Shannon-B. Crow Raven Jul 17 '14 at 19:15
  • 4
    Note, that this solution doesn't behave exactly as described in the question. Specifically `Mouse down and drag in the textbox should select only the text I've highlighted with the mouse.` doesn't work like desired. But still the shortest and most elegant solution :) – Marcus Mangelsdorf Sep 11 '15 at 12:24
  • Fantastic answer using `BeginInvoke`. With .net 3.5, VS 2008 I had to do this to get it to work. In the enter event: `BeginInvoke(New Action(Of MaskedTextBox)(AddressOf SelectText), sender)` this invokes a separate sub `Sub SelectText(ByVal Box As MaskedTextBox) Box.SelectAll() End Sub`. Works beautifully! – D_Bester Nov 12 '15 at 02:45
  • For WPF, I had to use a slightly different approach: Line1: Private Sub MyTextBox_Enter(sender As Object, e As EventArgs) Handles txtBox1.GotFocus, txtBox2.GotFocus Line2: If sender.name = "txtBox1" Then Line3: Dispatcher.BeginInvoke(DirectCast(Sub() txtBox1.SelectAll(), Action)) Line4: ElseIf sender.name = "txtBox2" Then Line5: Dispatcher.BeginInvoke(DirectCast(Sub() txtBox2.SelectAll(), Action)) Line6: End If Line7: End Sub – CoRrRan Mar 29 '17 at 14:25
  • Even shorter VB (in .Net 4.7) `BeginInvoke(Sub() MyTextBox.SelectAll())` – ourmandave Jun 05 '21 at 11:17
30

Your solution is good, but fails in one specific case. If you give the TextBox focus by selecting a range of text instead of just clicking, the alreadyFocussed flag doesn't get set to true, so when you click in the TextBox a second time, all the text gets selected.

Here is my version of the solution. I've also put the code into a class which inherits TextBox, so the logic is nicely hidden away.

public class MyTextBox : System.Windows.Forms.TextBox
{
    private bool _focused;

    protected override void OnEnter(EventArgs e)
    {
        base.OnEnter(e);
        if (MouseButtons == MouseButtons.None)
        {
            SelectAll();
            _focused = true;
        }
    }

    protected override void OnLeave(EventArgs e)
    {
        base.OnLeave(e);
        _focused = false;
    }

    protected override void OnMouseUp(MouseEventArgs mevent)
    {
        base.OnMouseUp(mevent);
        if (!_focused)
        {
            if (SelectionLength == 0)
                SelectAll();
            _focused = true;
        }
    }
}
nzhenry
  • 752
  • 8
  • 15
  • 2
    +1 for custom textbox suggestion and perfectly working solution! – Fueled Oct 05 '11 at 09:51
  • Terrific solution. Copied your code right into my solution, changed the namespace to protect the innocent, and worked perfectly. Thanks! – kenswdev Jan 28 '14 at 22:25
8

It's a bit kludgey, but in your click event, use SendKeys.Send( "{HOME}+{END}" );.

bluish
  • 26,356
  • 27
  • 122
  • 180
Todd Benning
  • 127
  • 2
4

A one line answer that I use...you might be kicking yourself...

In the Enter Event:

txtFilter.BeginInvoke(new MethodInvoker( txtFilter.SelectAll));

  • 1
    Nope, doesn't work. It selects all text, alright, but it also prevents the user from selecting just part of the text, among other problems. – Judah Gabriel Himango Apr 06 '09 at 22:03
  • Sorry, I must have misunderstood the behavior you were looking for. On enter it selects all, if you click and hold it select from beginning to your cursor. I suppose you could use what I have and replace SelectAll with your own select logic. http://www.notifywire.com/demos/2009-04-14_1248.swf –  Apr 14 '09 at 17:07
  • Works great! First click enters the box; then click and drag to select text. – D_Bester Dec 18 '14 at 04:44
  • Note: it doesn't work like a web browser's address bar. A web browser's address bar allows you to mouse down in the textbox and drag/select, even when the text box doesn't yet have focus. This solution doesn't solve that. If you're OK with that, cool, but it does not satisfy the requirements of this question. – Judah Gabriel Himango Aug 04 '16 at 15:54
4

Click event of textbox? Or even MouseCaptureChanged event works for me. - OK. doesn't work.

So you have to do 2 things:

private bool f = false;

private void textBox_MouseClick(object sender, MouseEventArgs e)
{ 
  if (this.f) { this.textBox.SelectAll(); }
  this.f = false;
}

private void textBox_Enter(object sender, EventArgs e)
{
  this.f = true;
  this.textBox.SelectAll();
}
private void textBox_MouseMove(object sender, MouseEventArgs e) // idea from the other answer
{
  this.f = false; 
}

Works for tabbing (through textBoxes to the one) as well - call SelectAll() in Enter just in case...

Jakub Kotrla
  • 257
  • 1
  • 6
  • Ok Jakub, that partially works. If I tab to the text box, it needs to focus. Will that work with your solution? (If you can show me how, I'll mark your answer as the correct answer.) – Judah Gabriel Himango Sep 18 '08 at 22:34
  • Jakub, now that you've posted the code, it seems to *sometimes* work. Not always; right now I'm clicking into the text box and it's not selecting all. – Judah Gabriel Himango Sep 19 '08 at 13:48
  • Sometimes I'll click into the text and it doesn't select all. It's like somehow the .f field isn't set to what it should be, and then SelectAll doesn't get called. Haven't seen this? – Judah Gabriel Himango Sep 20 '08 at 20:18
  • I know only that because of mouseMouve you can slow-click while move mouse (especially on wide letters) -> unset the flag. You can remove the code in mouseMove event, but than you get - after tabbgin to control and then clicking - reSelectAll - unable to select part of stirng on first drag – Jakub Kotrla Sep 20 '08 at 23:44
3

Here's a helper function taking the solution to the next level - reuse without inheritance.

    public static void WireSelectAllOnFocus( TextBox aTextBox )
    {
        bool lActive = false;
        aTextBox.GotFocus += new EventHandler( ( sender, e ) =>
        {
            if ( System.Windows.Forms.Control.MouseButtons == MouseButtons.None )
            {
                aTextBox.SelectAll();
                lActive = true;
            }
        } );

        aTextBox.Leave += new EventHandler( (sender, e ) => {
            lActive = false;
        } );

        aTextBox.MouseUp += new MouseEventHandler( (sender, e ) => {
            if ( !lActive )
            {
                lActive = true;
                if ( aTextBox.SelectionLength == 0 ) aTextBox.SelectAll();
            }   
        });
    }

To use this simply call the function passing a TextBox and it takes care of all the messy bits for you. I suggest wiring up all your text boxes in the Form_Load event. You can place this function in your form, or if your like me, somewhere in a utility class for even more reuse.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Ross K.
  • 101
  • 1
  • 2
3
'Inside the Enter event
TextBox1.SelectAll();

Ok, after trying it here is what you want:

  • On the Enter event start a flag that states that you have been in the enter event
  • On the Click event, if you set the flag, call .SelectAll() and reset the flag.
  • On the MouseMove event, set the entered flag to false, which will allow you to click highlight without having to enter the textbox first.

This selected all the text on entry, but allowed me to highlight part of the text afterwards, or allow you to highlight on the first click.

By request:

    bool entered = false;
    private void textBox1_Enter(object sender, EventArgs e)
    {
        entered = true;
        textBox1.SelectAll();   //From Jakub's answer.
    }

    private void textBox1_Click(object sender, EventArgs e)
    {
        if (entered) textBox1.SelectAll();
        entered = false;
    }

    private void textBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (entered) entered = false;
    }

For me, the tabbing into the control selects all the text.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
MagicKat
  • 9,695
  • 6
  • 32
  • 43
2

This is similar to nzhenry's popular answer, but I find it easier to not have to subclass:

Private LastFocused As Control = Nothing

Private Sub TextBox1_Enter(sender As Object, e As System.EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter
    If MouseButtons = Windows.Forms.MouseButtons.None Then LastFocused = sender
End Sub

Private Sub TextBox1_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave, TextBox2.Leave, TextBox3.Leave
    LastFocused = Nothing
End Sub

Private Sub TextBox1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp, TextBox2.MouseUp, TextBox3.MouseUp
    With CType(sender, TextBox)
        If LastFocused IsNot sender AndAlso .SelectionLength = 0 Then .SelectAll()
    End With
    LastFocused = sender
End Sub
Jimi
  • 29,621
  • 8
  • 43
  • 61
Chris
  • 21
  • 1
2

This worked for a WPF/XAML TextBox.

    private bool initialEntry = true;
    private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
    {
        if (initialEntry)
        {
            e.Handled = true;
            initialEntry = false;
            TextBox.SelectAll();
        }
    }
    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox.SelectAll();
        initialEntry = true;      
    }
slobs
  • 21
  • 1
1

SelectAll never worked for me.

This works.

ActiveControl = textBox1;
textBox1->SelectionStart = 0;
textBox1->SelectionLength = textBox1->Text->Length;
Adam Bruss
  • 1,654
  • 14
  • 18
1

I've found an even simpler solution:

To make sure all text is selected when clicking on a textBox, make sure that the Click handler calls the Enter handler. No need for extra variables!

Example:

private void textBox1_Click(object sender, EventArgs e){
        textBox1_Enter(sender, e);
    }

private void textBox1_Enter(object sender, EventArgs e){
        TextBox tb = ((TextBox)sender);
        tb.SelectAll();
    }
Pieter Heemeryck
  • 664
  • 5
  • 13
  • This doesn't work for focus via tabbing into the control, right? Also, what about when you want to select some text without selecting all? – Judah Gabriel Himango Apr 14 '15 at 14:47
  • Actually, it does work with tabbing into it! I just tested it in a dummy project using MS Visual C# 2010. The annoying thing with this solution is that you cannot select some text without selecting all. If you want to do just that, no code is needed of course, you could just use your mouse and select it (or using keyboard). – Pieter Heemeryck Apr 15 '15 at 00:57
  • And that's why this solution doesn't solve the problem presented: it doesn't behave like the browser address box, because you cannot click individual parts of the address without it selecting all the text. – Judah Gabriel Himango Apr 15 '15 at 16:18
  • Ok, I see what you mean. The title of the question and web browser's address bar example didn't indicate you should be able to select some part of text. You only mentioned this as a side in the last sentence of your question. Regards. – Pieter Heemeryck Apr 16 '15 at 14:16
0

Actually GotFocus is the right event (message really) that you are interested in, since no matter how you get to the control you’ll get this even eventually. The question is when do you call SelectAll().

Try this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
    }

    private delegate void SelectAllDelegate();    
    private IAsyncResult _selectAllar = null; //So we can clean up afterwards.

    //Catch the input focus event
    void textBox1_GotFocus(object sender, EventArgs e)
    {
        //We could have gotten here many ways (including mouse click)
        //so there could be other messages queued up already that might change the selection.
        //Don't call SelectAll here, since it might get undone by things such as positioning the cursor.
        //Instead use BeginInvoke on the form to queue up a message
        //to select all the text after everything caused by the current event is processed.
        this._selectAllar = this.BeginInvoke(new SelectAllDelegate(this._SelectAll));
    }

    private void _SelectAll()
    {
        //Clean-up the BeginInvoke
        if (this._selectAllar != null)
        {
            this.EndInvoke(this._selectAllar);
        }
        //Now select everything.
        this.textBox1.SelectAll();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

The following solution works for me. I added OnKeyDown and OnKeyUp event override to keep the TextBox text always selected.

    public class NumericTextBox : TextBox
{
    private bool _focused;
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        if (MouseButtons == MouseButtons.None)
        {
            this.SelectAll();
            _focused = true;
        }
    }
    protected override void OnEnter(EventArgs e)
    {
        base.OnEnter(e);
        if (MouseButtons == MouseButtons.None)
        {
            SelectAll();
            _focused = true;
        }
    }

    protected override void OnLeave(EventArgs e)
    {
        base.OnLeave(e);
        _focused = false;
    }

    protected override void OnMouseUp(MouseEventArgs mevent)
    {
        base.OnMouseUp(mevent);
        if (!_focused)
        {
            if (SelectionLength == 0)
                SelectAll();
            _focused = true;
        }
    }

    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);

        if (SelectionLength == 0)
            SelectAll();
        _focused = true;
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
       base.OnKeyDown(e);
       if (SelectionLength == 0)
            SelectAll();
        _focused = true;
    }
}
ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
abrfra
  • 634
  • 2
  • 6
  • 24
0

I called SelectAll inside MouseUp event and it worked fine for me.

    private bool _tailTextBoxFirstClick = false;

    private void textBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if(_textBoxFirstClick)           
            textBox1.SelectAll();

        _textBoxFirstClick = false;
    }  

    private void textBox1_Leave(object sender, EventArgs e)
    {
        _textBoxFirstClick = true;
        textBox1.Select(0, 0);
    }
Sreejith K.
  • 163
  • 1
  • 9
  • Yeah, see the other answers (and comments) for why this doesn't work in all scenarios. – Judah Gabriel Himango Oct 27 '09 at 01:23
  • I did not check for tab for this solution. My bad. Thanks for pointing out. Glad to see that you have the complete solution now. And also glad to know that my suggestion for MouseUp was included in your solution. – Sreejith K. Oct 27 '09 at 16:32
0

Set the selction when you leave the control. It will be there when you get back. Tab around the form and when you return to the control, all the text will be selected.

If you go in by mouse, then the caret will rightly be placed at the point where you clicked.

private void maskedTextBox1_Leave(object sender, CancelEventArgs e)
    {
        maskedTextBox1.SelectAll();
    }
Rob
  • 4,927
  • 12
  • 49
  • 54
Joel
  • 1
0

Just derive a class from TextBox or MaskedTextBox:

public class SMaskedTextBox : MaskedTextBox
{
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        this.SelectAll();
    }
}

And use it on your forms.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Very simple solution:

    private bool _focusing = false;

    protected override void OnEnter( EventArgs e )
    {
        _focusing = true;
        base.OnEnter( e );
    }

    protected override void OnMouseUp( MouseEventArgs mevent )
    {
        base.OnMouseUp( mevent );

        if( _focusing )
        {
            this.SelectAll();
            _focusing = false;
        }
    }

EDIT: Original OP was in particular concerned about the mouse-down / text-selection / mouse-up sequence, in which case the above simple solution would end up with text being partially selected.

This should solve* the problem (in practice I intercept WM_SETCURSOR):

    protected override void WndProc( ref Message m )
    {
        if( m.Msg == 32 ) //WM_SETCURSOR=0x20
        {
              this.SelectAll(); // or your custom logic here                
        }

        base.WndProc( ref m );
    }

*Actually the following sequence ends up with partial text selection but then if you move the mouse over the textbox all text will be selected again:

mouse-down / text-selection / mouse-move-out-textbox / mouse-up

Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50
0

Why don't you simply use the MouseDown-Event of the text box? It works fine for me and doesn't need an additional boolean. Very clean and simple, eg.:

private void textbox_MouseDown(object sender, MouseEventArgs e) {
    if (textbox != null && !string.IsNullOrEmpty(textbox.Text))
    {
        textbox.SelectAll();
    } }
  • Nope, couple problems with this: doesn't account for if the textbox already has focus (we don't want to select-all every mouse down, just when the textbox didn't have focus), doesn't let you select just a portion of the text, doesn't work when bring focus via tabbing to the textbox. – Judah Gabriel Himango Nov 22 '08 at 19:32
0

I find this work best, when mouse click and not release immediately:

    private bool SearchBoxInFocusAlready = false;
    private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
    {
        SearchBoxInFocusAlready = false;
    }

    private void SearchBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.ButtonState == MouseButtonState.Released && e.ChangedButton == MouseButton.Left &&
            SearchBox.SelectionLength == 0 && SearchBoxInFocusAlready == false)
        {
            SearchBox.SelectAll();
        }

        SearchBoxInFocusAlready = true;
    }
Hawston
  • 313
  • 3
  • 5
0

My Solution is pretty primitive but works fine for my purpose

private async void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    if (sender is TextBox)
    {
        await Task.Delay(100);
        (sender as TextBox).SelectAll();
    }
}
BlueWizard
  • 372
  • 4
  • 19
  • Doesn't work when you want to mouse down to select a bunch of text, drag your mouse, then mouse up. Your code will clear the selection and select everything. – Judah Gabriel Himango Jul 20 '15 at 18:24
  • @JudahHimango Jup. If you single click it will select everything. If you click and drag it will select only the selection. At least the Browserbar in Firefox shows exactly this behaviour. – BlueWizard Jul 20 '15 at 22:07
  • isn't it a race condition, though? If I manage to quickly select some text with the mouse, then the .SelectAll() will fire milliseconds later, overwritting my selection. – Judah Gabriel Himango Jul 22 '15 at 16:06
  • 1
    Ok, if you are quick at selecting things than this thing will work against you. – BlueWizard Jul 22 '15 at 17:46
0

Have you tried the solution suggested on the MSDN Forum "Windows Forms General" which simply subclasses TextBox?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
huseyint
  • 14,953
  • 15
  • 56
  • 78
0

For a group of textboxes in a form:

private System.Windows.Forms.TextBox lastFocus;   

private void textBox_GotFocus(object sender, System.Windows.Forms.MouseEventArgs e)   
{
    TextBox senderTextBox = sender as TextBox;
    if (lastFocus!=senderTextBox){
        senderTextBox.SelectAll();
    }
    lastFocus = senderTextBox;   
}
JohnD
  • 3,884
  • 1
  • 28
  • 40
Yfiua
  • 1
  • 1
    This doesn't work properly; see my replies to the other answers that suggest .SelectAll(). It doesn't work because if you enter the textbox while trying to select text, it breaks your text selection by selecting all the text. You only want to select text if focus entered the textbox via mouse up or tabbing into it, but if the focus was caused via mouse down. – Judah Gabriel Himango May 26 '11 at 19:37
0

I know this was already solved but I have a suggestion that I think is actually rather simple.

In the mouse up event all you have to do is place

if(textBox.SelectionLength = 0)
{
    textBox.SelectAll();
}

It seems to work for me in VB.NET (I know this is a C# question... sadly I'm forced to use VB at my job.. and I was having this issue, which is what brought me here...)

I haven't found any problems with it yet.. except for the fact that it doesn't immediately select on click, but I was having problems with that....

Eluem
  • 1
  • 1
    The original request wanted this to work when you tab into the field as well. – Don Kirkby Jan 13 '12 at 17:24
  • 2
    Yep, this doesn't work for all the scenarios. It only works when you click into the textbox. And even then, if doesn't behave as a browser address bar behaves when selection already exists in the text box. – Judah Gabriel Himango Jan 16 '12 at 19:41
0
private bool _isSelected = false;
private void textBox_Validated(object sender, EventArgs e)
{
    _isSelected = false;
}

private void textBox_MouseClick(object sender, MouseEventArgs e)
{
    SelectAllText(textBox);
}

private void textBox_Enter(object sender, EventArgs e)
{
    SelectAllText(textBox);
}

private void SelectAllText(TextBox text)
{
    if (!_isSelected)
    {
        _isSelected = true;
        textBox.SelectAll();
    }
}
Nescio
  • 27,645
  • 10
  • 53
  • 72
  • I just tested with a RichTextBox. Doesn't work. Clicking into the textbox doesn't appear to select all text. (Because it's getting deselected on mouse down, when the caret is placed at the cursor.) – Judah Gabriel Himango Sep 18 '08 at 23:07
0

Interestingly, a ComboBox with DropDownStyle=Simple has pretty much exactly the behaviour you are looking for, I think.

(If you reduce the height of the control to not show the list - and then by a couple of pixels more - there's no effective difference between the ComboBox and the TextBox.)

-1

The answer can be actually quite more simple than ALL of the above, for example (in WPF):

public void YourTextBox_MouseEnter(object sender, MouseEventArgs e)
    {
        YourTextBox.Focus();
        YourTextBox.SelectAll();
    }

of course I can't know how you want to use this code, but the main part to look at here is: First call .Focus() and then call .SelectAll();

MDB
  • 7
  • 1
  • This doesn't work, and is a duplicate of other answers. For example, if you mouse down in the textbox, drag, it should select part of the text. This breaks that and doesn't selects all. – Judah Gabriel Himango Jul 27 '16 at 15:18
-1

I created a new VB.Net Wpf project. I created one TextBox and used the following for the codebehind:

Class MainWindow 

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        AddHandler PreviewMouseLeftButtonDown, New MouseButtonEventHandler(AddressOf SelectivelyIgnoreMouseButton)
        AddHandler GotKeyboardFocus, New KeyboardFocusChangedEventHandler(AddressOf SelectAllText)
        AddHandler MouseDoubleClick, New MouseButtonEventHandler(AddressOf SelectAllText)
    End Sub

    Private Shared Sub SelectivelyIgnoreMouseButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
        ' Find the TextBox
        Dim parent As DependencyObject = TryCast(e.OriginalSource, UIElement)
        While parent IsNot Nothing AndAlso Not (TypeOf parent Is TextBox)
            parent = VisualTreeHelper.GetParent(parent)
        End While

        If parent IsNot Nothing Then
            Dim textBox As Object = DirectCast(parent, TextBox)
            If Not textBox.IsKeyboardFocusWithin Then
                ' If the text box is not yet focussed, give it the focus and
                ' stop further processing of this click event.
                textBox.Focus()
                e.Handled = True
            End If
        End If
    End Sub

    Private Shared Sub SelectAllText(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim textBox As Object = TryCast(e.OriginalSource, TextBox)
        If textBox IsNot Nothing Then
            textBox.SelectAll()
        End If
    End Sub

End Class
Marcus Mangelsdorf
  • 2,852
  • 1
  • 30
  • 40
BSalita
  • 8,420
  • 10
  • 51
  • 68
-1

just use selectall() on enter and click events

private void textBox1_Enter(object sender, EventArgs e)
        {

            textBox1.SelectAll();
        }
        private void textBox1_Click(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }
EKanadily
  • 3,831
  • 3
  • 35
  • 33
-1

This is working for me in .NET 2005 -

    ' * if the mouse button is down, do not run the select all.
    If MouseButtons = Windows.Forms.MouseButtons.Left Then
        Exit Sub
    End If

 ' * OTHERWISE INVOKE THE SELECT ALL AS DISCUSSED.
Cody
  • 1
  • 1
-1

The below seems to work. The enter event handles the tabbing to the control and the MouseDown works when the control is clicked.

    private ########### void textBox1_Enter(object sender, EventArgs e)
    {
        textBox1.SelectAll();
    }

    private void textBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (textBox1.Focused)
            textBox1.SelectAll();
    }
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
benPearce
  • 37,735
  • 14
  • 62
  • 96