Auto highlight text in a textbox control

2019-01-08 20:14发布

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

标签: c# textbox
15条回答
ら.Afraid
2楼-- · 2019-01-08 21:05

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(); 
    }
查看更多
3楼-- · 2019-01-08 21:06

It is very easy to achieve with built in method SelectAll

Simply cou can write this:

txtTextBox.Focus();
txtTextBox.SelectAll();

And everything in textBox will be selected :)

查看更多
Root(大扎)
4楼-- · 2019-01-08 21:08

In window form c#. If you use Enter event it will not work. try to use MouseUp event

    bool FlagEntered;
    private void textBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if ((sender as TextBox).SelectedText == "" && !FlagEntered)
        {
            (sender as TextBox).SelectAll();
            FlagEntered = true;
        }
    }

    private void textBox1_Leave(object sender, EventArgs e)
    {
        FlagEntered = false;
    }
查看更多
登录 后发表回答