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(); }
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.
E-mail
Theme design by Jelle Druyts