自动突出显示文本框控件中的文本

Kev*_*vin 35 c# textbox

当控件获得焦点时,如何在文本框控件中自动突出显示文本.

Ree*_*sey 52

在Windows窗体和WPF中:

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
Run Code Online (Sandbox Code Playgroud)


beo*_*eon 10

在asp.net中:

textBox.Attributes.Add("onfocus","this.select();");
Run Code Online (Sandbox Code Playgroud)


小智 9

如果要为整个WPF应用程序执行此操作,可以执行以下操作: - 在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(); 
    }
Run Code Online (Sandbox Code Playgroud)

  • 用于Tabbing到TextBox.点击其中没有那么好用.如果单击文本,它会快速突出显示,然后在显示之前取消突出显示,就像光标位于单击的位置一样. (2认同)

Rox*_*Pro 6

使用内置方法很容易实现 SelectAll

简单的你可以这样写:

txtTextBox.Focus();
txtTextBox.SelectAll();
Run Code Online (Sandbox Code Playgroud)

文本框中的所有内容都将被选中:)


小智 5

如果您打算通过鼠标单击突出显示文本框中的文本,则可以通过添加以下内容来简化:

this.textBox1.Click += new System.EventHandler(textBox1_Click);
Run Code Online (Sandbox Code Playgroud)

在:

partial class Form1
{
    private void InitializeComponent()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

其中textBox1是位于Form1中的相关文本框的名称

然后创建方法定义:

void textBox1_Click(object sender, System.EventArgs e)
{
    textBox1.SelectAll();
}
Run Code Online (Sandbox Code Playgroud)

在:

public partial class Form1 : Form
{

}
Run Code Online (Sandbox Code Playgroud)