Selecting TextBox Text Part II#

Thanks to Daniel Moth for the tip on using a Timer instead of a thread to select text in the textbox. Basically it negates the need for Sleep() and/or Invoke() and makes for a bit cleaner code. Here is the updated code.  I have left the thread version in the GotFocus but have commented it out.

 

private TextBox currentTB = null;
    private void GenericTextBox_GotFocus(object sender, System.EventArgs e)
    {
        this.currentTB = (TextBox)sender;

        //Use a timer to select all. This will negate the need for Invoke or sleep in the thread. Thanks to Daniel Moth for this :-)
        Timer t = new Timer();
        t.Interval = 10;
        t.Tick+=new EventHandler(t_Tick);
        t.Enabled = true;

        /*
         * USE THIS SECTION TO USE A THREAD BUT THE TIMER METHOD IS BETTER/CLEANER
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(SelectAll));
        t.Start();
        */

    }

    private void SelectAll()
    {
        if(this.currentTB!=null)
        {
            //Usuall the Invoke should finish after the got focus event finishs. If you experience problems add a sleep
            //System.Threading.Thread.Sleep(50);
            currentTB.Invoke(new EventHandler(InvokeSelectAll));
            currentTB = null;
        }
    }

    private void InvokeSelectAll(object sender, System.EventArgs e)
    {
        ((TextBox)sender).SelectAll();
    }

    private void t_Tick(object sender, EventArgs e)
    {
        ((Timer)sender).Enabled =false;
        this.currentTB.SelectAll();
    }


Tuesday, March 22, 2005 8:46:17 AM (Eastern Standard Time, UTC-05:00) #    Comments [0]  |  Tracked by:
"roulette" (roulette) [Trackback]
"Selecting Control Text" (Mark Arteaga) [Trackback]

 

Comments are closed.
All content © 2008, Mark Arteaga
On this page
Related Sites
Archives
Sitemap
Disclaimer

Powered by: newtelligence dasBlog 1.9.7174.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts