Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto highlight text in a textbox control

Tags:

c#

textbox

How do you auto highlight text in a textbox control when the control gains focus.

like image 417
Kevin Avatar asked Jan 28 '10 00:01

Kevin


2 Answers

In Windows Forms and WPF:

textbox.SelectionStart = 0; textbox.SelectionLength = textbox.Text.Length; 
like image 58
Reed Copsey Avatar answered Sep 21 '22 17:09

Reed Copsey


If you want to do it for your whole WPF application you can do the following: - In the file App.xaml.cs

    protected override void OnStartup(StartupEventArgs e)     {         //works for tab into textbox         EventManager.RegisterClassHandler(typeof(TextBox),             TextBox.GotFocusEvent,             new RoutedEventHandler(TextBox_GotFocus));         //works for click textbox         EventManager.RegisterClassHandler(typeof(Window),             Window.GotMouseCaptureEvent,             new RoutedEventHandler(Window_MouseCapture));          base.OnStartup(e);     }     private void TextBox_GotFocus(object sender, RoutedEventArgs e)     {         (sender as TextBox).SelectAll();     }      private void Window_MouseCapture(object sender, RoutedEventArgs e)     {         var textBox = e.OriginalSource as TextBox;         if (textBox != null)              textBox.SelectAll();      } 
like image 21
MontrealKid Avatar answered Sep 18 '22 17:09

MontrealKid