Textbox.SelectionStart

10,627

Solution 1

Your code as is works fine for me (I'm assuming your BGW is started and you're calling ReportProgress of course).

My guess here is that your code is working for you too, but perhaps your TextBox doesn't have focus so you can't see the selected text.

If this is your problem, set the TextBox's HideSelection property to false. This will allow the TextBox's selected text to display selected (highlighted) even if the TextBox doesn't have focus.

You can also query your TextBox's SelectedText property to get the control's selected text, even if it isn't displayed as such.

Solution 2

Make sure that if you are running this code on the same thread which created the object (the GuiThread). A background worker is likely not the same thread as the one where the textbox was created. You can ensure that you are using the GuiThread by calling Invoke on the control (which you can refer to with "this").

So.. do something like

this.Invoke().

You'll need to pass it a delegate, so move your textbox selection logic into a separate method, and then pass that method into the Invoke() call.

Edit:

Your code will probably look something like this:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.Invoke(new Action<TextBox, int, int>(UpdateTextboxSelection), new object[] { textBox1, (int)e.UserState, 1 });
}

private void UpdateTextboxSelection(TextBox t, int start, int length)
{
    t.SelectionStart = start;
    t.SelectionLength = length;
    t.Focus(); // to make sure the box is in focus so that you see the selection
}

Edit 2: Note, I have not actually tried to see if this works, this is just a common problem that I have always had when wondering why certain UI things aren't doing anything, I notice I am running on a different thread and when I start using the GUI Thread it works.

Edit 3: I just ran a test. Make sure to Focus() on the textbox when you are done. It is possible that the text selection is being set as you are intending, but you don't see it because the box is not in focus.

Share:
10,627
Guye Incognito
Author by

Guye Incognito

My background is in architecture (real world architecture!) Currently studying Higher Diploma in Computing conversion course in D.I.T.

Updated on June 04, 2022

Comments

  • Guye Incognito
    Guye Incognito almost 2 years

    I'm trying to use the SelectionStart and SelectionLength properties for a textbox. It is having no effect, but there are no errors either. It's actually part of a background worker ProgressChanged method, but I've tried the SelectionStart and SelectionLength in isolation in a test solution and it is the same.. nothing happens..

    Any ideas? Thanks!!!

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    {
        // Update the GUI as the music is playing
        textBox1.SelectionStart = ((int)e.UserState);
        textBox1.SelectionLength = (1);
    }